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/MCAsmInfo.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/MCObjectFileInfo.h"
25 #include "llvm/MC/MCObjectWriter.h"
26 #include "llvm/MC/MCSectionWasm.h"
27 #include "llvm/MC/MCSymbolWasm.h"
28 #include "llvm/MC/MCValue.h"
29 #include "llvm/MC/MCWasmObjectWriter.h"
30 #include "llvm/Support/Casting.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/LEB128.h"
34 #include "llvm/Support/StringSaver.h"
39 #define DEBUG_TYPE "mc"
43 // For patching purposes, we need to remember where each section starts, both
44 // for patching up the section size field, and for patching up references to
45 // locations within the section.
46 struct SectionBookkeeping {
47 // Where the size of the section is written.
49 // Where the contents of the section starts (after the header).
50 uint64_t ContentsOffset;
53 // The signature of a wasm function, in a struct capable of being used as a
55 struct WasmFunctionType {
56 // Support empty and tombstone instances, needed by DenseMap.
57 enum { Plain, Empty, Tombstone } State;
59 // The return types of the function.
60 SmallVector<wasm::ValType, 1> Returns;
62 // The parameter types of the function.
63 SmallVector<wasm::ValType, 4> Params;
65 WasmFunctionType() : State(Plain) {}
67 bool operator==(const WasmFunctionType &Other) const {
68 return State == Other.State && Returns == Other.Returns &&
69 Params == Other.Params;
73 // Traits for using WasmFunctionType in a DenseMap.
74 struct WasmFunctionTypeDenseMapInfo {
75 static WasmFunctionType getEmptyKey() {
76 WasmFunctionType FuncTy;
77 FuncTy.State = WasmFunctionType::Empty;
80 static WasmFunctionType getTombstoneKey() {
81 WasmFunctionType FuncTy;
82 FuncTy.State = WasmFunctionType::Tombstone;
85 static unsigned getHashValue(const WasmFunctionType &FuncTy) {
86 uintptr_t Value = FuncTy.State;
87 for (wasm::ValType Ret : FuncTy.Returns)
88 Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Ret));
89 for (wasm::ValType Param : FuncTy.Params)
90 Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Param));
93 static bool isEqual(const WasmFunctionType &LHS,
94 const WasmFunctionType &RHS) {
99 // A wasm data segment. A wasm binary contains only a single data section
100 // but that can contain many segments, each with their own virtual location
101 // in memory. Each MCSection data created by llvm is modeled as its own
102 // wasm data segment.
103 struct WasmDataSegment {
104 MCSectionWasm *Section;
109 SmallVector<char, 4> Data;
112 // A wasm import to be written into the import section.
114 StringRef ModuleName;
120 // A wasm function to be written into the function section.
121 struct WasmFunction {
123 const MCSymbolWasm *Sym;
126 // A wasm export to be written into the export section.
133 // A wasm global to be written into the global section.
138 uint64_t InitialValue;
139 uint32_t ImportIndex;
142 // Information about a single relocation.
143 struct WasmRelocationEntry {
144 uint64_t Offset; // Where is the relocation.
145 const MCSymbolWasm *Symbol; // The symbol to relocate with.
146 int64_t Addend; // A value to add to the symbol.
147 unsigned Type; // The type of the relocation.
148 const MCSectionWasm *FixupSection;// The section the relocation is targeting.
150 WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
151 int64_t Addend, unsigned Type,
152 const MCSectionWasm *FixupSection)
153 : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
154 FixupSection(FixupSection) {}
156 bool hasAddend() const {
158 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
159 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
160 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
167 void print(raw_ostream &Out) const {
168 Out << "Off=" << Offset << ", Sym=" << *Symbol << ", Addend=" << Addend
170 << ", FixupSection=" << FixupSection->getSectionName();
173 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
174 LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
179 raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
185 class WasmObjectWriter : public MCObjectWriter {
186 /// Helper struct for containing some precomputed information on symbols.
187 struct WasmSymbolData {
188 const MCSymbolWasm *Symbol;
191 // Support lexicographic sorting.
192 bool operator<(const WasmSymbolData &RHS) const { return Name < RHS.Name; }
195 /// The target specific Wasm writer instance.
196 std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
198 // Relocations for fixing up references in the code section.
199 std::vector<WasmRelocationEntry> CodeRelocations;
201 // Relocations for fixing up references in the data section.
202 std::vector<WasmRelocationEntry> DataRelocations;
204 // Index values to use for fixing up call_indirect type indices.
205 // Maps function symbols to the index of the type of the function
206 DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
207 // Maps function symbols to the table element index space. Used
208 // for TABLE_INDEX relocation types (i.e. address taken functions).
209 DenseMap<const MCSymbolWasm *, uint32_t> IndirectSymbolIndices;
210 // Maps function/global symbols to the function/global index space.
211 DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices;
213 DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo>
215 SmallVector<WasmFunctionType, 4> FunctionTypes;
216 SmallVector<WasmGlobal, 4> Globals;
217 unsigned NumGlobalImports = 0;
219 // TargetObjectWriter wrappers.
220 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
221 unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
222 return TargetObjectWriter->getRelocType(Target, Fixup);
225 void startSection(SectionBookkeeping &Section, unsigned SectionId,
226 const char *Name = nullptr);
227 void endSection(SectionBookkeeping &Section);
230 WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
231 raw_pwrite_stream &OS)
232 : MCObjectWriter(OS, /*IsLittleEndian=*/true),
233 TargetObjectWriter(std::move(MOTW)) {}
236 ~WasmObjectWriter() override;
238 void reset() override {
239 CodeRelocations.clear();
240 DataRelocations.clear();
242 SymbolIndices.clear();
243 IndirectSymbolIndices.clear();
244 FunctionTypeIndices.clear();
245 FunctionTypes.clear();
247 MCObjectWriter::reset();
248 NumGlobalImports = 0;
251 void writeHeader(const MCAssembler &Asm);
253 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
254 const MCFragment *Fragment, const MCFixup &Fixup,
255 MCValue Target, uint64_t &FixedValue) override;
257 void executePostLayoutBinding(MCAssembler &Asm,
258 const MCAsmLayout &Layout) override;
260 void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
262 void writeString(const StringRef Str) {
263 encodeULEB128(Str.size(), getStream());
267 void writeValueType(wasm::ValType Ty) {
268 encodeSLEB128(int32_t(Ty), getStream());
271 void writeTypeSection(ArrayRef<WasmFunctionType> FunctionTypes);
272 void writeImportSection(ArrayRef<WasmImport> Imports);
273 void writeFunctionSection(ArrayRef<WasmFunction> Functions);
274 void writeTableSection(uint32_t NumElements);
275 void writeMemorySection(uint32_t DataSize);
276 void writeGlobalSection();
277 void writeExportSection(ArrayRef<WasmExport> Exports);
278 void writeElemSection(ArrayRef<uint32_t> TableElems);
279 void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
280 ArrayRef<WasmFunction> Functions);
281 void writeDataSection(ArrayRef<WasmDataSegment> Segments);
282 void writeNameSection(ArrayRef<WasmFunction> Functions,
283 ArrayRef<WasmImport> Imports,
284 uint32_t NumFuncImports);
285 void writeCodeRelocSection();
286 void writeDataRelocSection();
287 void writeLinkingMetaDataSection(
288 ArrayRef<WasmDataSegment> Segments, uint32_t DataSize,
289 SmallVector<std::pair<StringRef, uint32_t>, 4> SymbolFlags,
290 bool HasStackPointer, uint32_t StackPointerGlobal);
292 uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
293 void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
294 uint64_t ContentsOffset);
296 void writeRelocations(ArrayRef<WasmRelocationEntry> Relocations);
297 uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
298 uint32_t getFunctionType(const MCSymbolWasm& Symbol);
299 uint32_t registerFunctionType(const MCSymbolWasm& Symbol);
302 } // end anonymous namespace
304 WasmObjectWriter::~WasmObjectWriter() {}
306 // Write out a section header and a patchable section size field.
307 void WasmObjectWriter::startSection(SectionBookkeeping &Section,
310 assert((Name != nullptr) == (SectionId == wasm::WASM_SEC_CUSTOM) &&
311 "Only custom sections can have names");
313 DEBUG(dbgs() << "startSection " << SectionId << ": " << Name << "\n");
314 encodeULEB128(SectionId, getStream());
316 Section.SizeOffset = getStream().tell();
318 // The section size. We don't know the size yet, so reserve enough space
319 // for any 32-bit value; we'll patch it later.
320 encodeULEB128(UINT32_MAX, getStream());
322 // The position where the section starts, for measuring its size.
323 Section.ContentsOffset = getStream().tell();
325 // Custom sections in wasm also have a string identifier.
326 if (SectionId == wasm::WASM_SEC_CUSTOM) {
328 writeString(StringRef(Name));
332 // Now that the section is complete and we know how big it is, patch up the
333 // section size field at the start of the section.
334 void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
335 uint64_t Size = getStream().tell() - Section.ContentsOffset;
336 if (uint32_t(Size) != Size)
337 report_fatal_error("section size does not fit in a uint32_t");
339 DEBUG(dbgs() << "endSection size=" << Size << "\n");
341 // Write the final section size to the payload_len field, which follows
342 // the section id byte.
344 unsigned SizeLen = encodeULEB128(Size, Buffer, 5);
345 assert(SizeLen == 5);
346 getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset);
349 // Emit the Wasm header.
350 void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
351 writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic)));
352 writeLE32(wasm::WasmVersion);
355 void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
356 const MCAsmLayout &Layout) {
359 void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
360 const MCAsmLayout &Layout,
361 const MCFragment *Fragment,
362 const MCFixup &Fixup, MCValue Target,
363 uint64_t &FixedValue) {
364 MCAsmBackend &Backend = Asm.getBackend();
365 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
366 MCFixupKindInfo::FKF_IsPCRel;
367 const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
368 uint64_t C = Target.getConstant();
369 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
370 MCContext &Ctx = Asm.getContext();
372 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
373 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
374 "Should not have constructed this");
376 // Let A, B and C being the components of Target and R be the location of
377 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
378 // If it is pcrel, we want to compute (A - B + C - R).
380 // In general, Wasm has no relocations for -B. It can only represent (A + C)
381 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
382 // replace B to implement it: (A - R - K + C)
386 "No relocation available to represent this relative expression");
390 const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
392 if (SymB.isUndefined()) {
393 Ctx.reportError(Fixup.getLoc(),
394 Twine("symbol '") + SymB.getName() +
395 "' can not be undefined in a subtraction expression");
399 assert(!SymB.isAbsolute() && "Should have been folded");
400 const MCSection &SecB = SymB.getSection();
401 if (&SecB != &FixupSection) {
402 Ctx.reportError(Fixup.getLoc(),
403 "Cannot represent a difference across sections");
407 uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
408 uint64_t K = SymBOffset - FixupOffset;
413 // We either rejected the fixup or folded B into C at this point.
414 const MCSymbolRefExpr *RefA = Target.getSymA();
415 const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
417 if (SymA && SymA->isVariable()) {
418 const MCExpr *Expr = SymA->getVariableValue();
419 const auto *Inner = cast<MCSymbolRefExpr>(Expr);
420 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
421 llvm_unreachable("weakref used in reloc not yet implemented");
424 // Put any constant offset in an addend. Offsets can be negative, and
425 // LLVM expects wrapping, in contrast to wasm's immediates which can't
426 // be negative and don't wrap.
430 SymA->setUsedInReloc();
435 unsigned Type = getRelocType(Target, Fixup);
437 WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
438 DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
440 if (FixupSection.hasInstructions())
441 CodeRelocations.push_back(Rec);
443 DataRelocations.push_back(Rec);
446 // Write X as an (unsigned) LEB value at offset Offset in Stream, padded
447 // to allow patching.
449 WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
451 unsigned SizeLen = encodeULEB128(X, Buffer, 5);
452 assert(SizeLen == 5);
453 Stream.pwrite((char *)Buffer, SizeLen, Offset);
456 // Write X as an signed LEB value at offset Offset in Stream, padded
457 // to allow patching.
459 WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) {
461 unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
462 assert(SizeLen == 5);
463 Stream.pwrite((char *)Buffer, SizeLen, Offset);
466 // Write X as a plain integer value at offset Offset in Stream.
467 static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
469 support::endian::write32le(Buffer, X);
470 Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
473 static const MCSymbolWasm* ResolveSymbol(const MCSymbolWasm& Symbol) {
474 if (Symbol.isVariable()) {
475 const MCExpr *Expr = Symbol.getVariableValue();
476 auto *Inner = cast<MCSymbolRefExpr>(Expr);
477 return cast<MCSymbolWasm>(&Inner->getSymbol());
482 // Compute a value to write into the code at the location covered
483 // by RelEntry. This value isn't used by the static linker, since
484 // we have addends; it just serves to make the code more readable
485 // and to make standalone wasm modules directly usable.
487 WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
488 const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
490 // For undefined symbols, use a hopefully invalid value.
491 if (!Sym->isDefined(/*SetUsed=*/false))
494 uint32_t GlobalIndex = SymbolIndices[Sym];
495 const WasmGlobal& Global = Globals[GlobalIndex - NumGlobalImports];
496 uint64_t Address = Global.InitialValue + RelEntry.Addend;
498 // Ignore overflow. LLVM allows address arithmetic to silently wrap.
499 uint32_t Value = Address;
504 static void addData(SmallVectorImpl<char> &DataBytes,
505 MCSectionWasm &DataSection) {
506 DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
508 DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
510 for (const MCFragment &Frag : DataSection) {
511 if (Frag.hasInstructions())
512 report_fatal_error("only data supported in data sections");
514 if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
515 if (Align->getValueSize() != 1)
516 report_fatal_error("only byte values supported for alignment");
517 // If nops are requested, use zeros, as this is the data section.
518 uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
519 uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(),
520 Align->getAlignment()),
522 Align->getMaxBytesToEmit());
523 DataBytes.resize(Size, Value);
524 } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
525 DataBytes.insert(DataBytes.end(), Fill->getSize(), Fill->getValue());
527 const auto &DataFrag = cast<MCDataFragment>(Frag);
528 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
530 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
534 DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
537 uint32_t WasmObjectWriter::getRelocationIndexValue(
538 const WasmRelocationEntry &RelEntry) {
539 switch (RelEntry.Type) {
540 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
541 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
542 if (!IndirectSymbolIndices.count(RelEntry.Symbol))
543 report_fatal_error("symbol not found table index space: " +
544 RelEntry.Symbol->getName());
545 return IndirectSymbolIndices[RelEntry.Symbol];
546 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
547 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
548 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
549 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
550 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
551 if (!SymbolIndices.count(RelEntry.Symbol))
552 report_fatal_error("symbol not found function/global index space: " +
553 RelEntry.Symbol->getName());
554 return SymbolIndices[RelEntry.Symbol];
555 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
556 if (!TypeIndices.count(RelEntry.Symbol))
557 report_fatal_error("symbol not found in type index space: " +
558 RelEntry.Symbol->getName());
559 return TypeIndices[RelEntry.Symbol];
561 llvm_unreachable("invalid relocation type");
565 // Apply the portions of the relocation records that we can handle ourselves
567 void WasmObjectWriter::applyRelocations(
568 ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
569 raw_pwrite_stream &Stream = getStream();
570 for (const WasmRelocationEntry &RelEntry : Relocations) {
571 uint64_t Offset = ContentsOffset +
572 RelEntry.FixupSection->getSectionOffset() +
575 DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
576 switch (RelEntry.Type) {
577 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
578 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
579 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
580 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB: {
581 uint32_t Index = getRelocationIndexValue(RelEntry);
582 WritePatchableSLEB(Stream, Index, Offset);
585 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
586 uint32_t Index = getRelocationIndexValue(RelEntry);
587 WriteI32(Stream, Index, Offset);
590 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
591 uint32_t Value = getProvisionalValue(RelEntry);
592 WritePatchableSLEB(Stream, Value, Offset);
595 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB: {
596 uint32_t Value = getProvisionalValue(RelEntry);
597 WritePatchableLEB(Stream, Value, Offset);
600 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32: {
601 uint32_t Value = getProvisionalValue(RelEntry);
602 WriteI32(Stream, Value, Offset);
606 llvm_unreachable("invalid relocation type");
611 // Write out the portions of the relocation records that the linker will
613 void WasmObjectWriter::writeRelocations(
614 ArrayRef<WasmRelocationEntry> Relocations) {
615 raw_pwrite_stream &Stream = getStream();
616 for (const WasmRelocationEntry& RelEntry : Relocations) {
618 uint64_t Offset = RelEntry.Offset +
619 RelEntry.FixupSection->getSectionOffset();
620 uint32_t Index = getRelocationIndexValue(RelEntry);
622 encodeULEB128(RelEntry.Type, Stream);
623 encodeULEB128(Offset, Stream);
624 encodeULEB128(Index, Stream);
625 if (RelEntry.hasAddend())
626 encodeSLEB128(RelEntry.Addend, Stream);
630 void WasmObjectWriter::writeTypeSection(
631 ArrayRef<WasmFunctionType> FunctionTypes) {
632 if (FunctionTypes.empty())
635 SectionBookkeeping Section;
636 startSection(Section, wasm::WASM_SEC_TYPE);
638 encodeULEB128(FunctionTypes.size(), getStream());
640 for (const WasmFunctionType &FuncTy : FunctionTypes) {
641 encodeSLEB128(wasm::WASM_TYPE_FUNC, getStream());
642 encodeULEB128(FuncTy.Params.size(), getStream());
643 for (wasm::ValType Ty : FuncTy.Params)
645 encodeULEB128(FuncTy.Returns.size(), getStream());
646 for (wasm::ValType Ty : FuncTy.Returns)
653 void WasmObjectWriter::writeImportSection(ArrayRef<WasmImport> Imports) {
657 SectionBookkeeping Section;
658 startSection(Section, wasm::WASM_SEC_IMPORT);
660 encodeULEB128(Imports.size(), getStream());
661 for (const WasmImport &Import : Imports) {
662 writeString(Import.ModuleName);
663 writeString(Import.FieldName);
665 encodeULEB128(Import.Kind, getStream());
667 switch (Import.Kind) {
668 case wasm::WASM_EXTERNAL_FUNCTION:
669 encodeULEB128(Import.Type, getStream());
671 case wasm::WASM_EXTERNAL_GLOBAL:
672 encodeSLEB128(int32_t(Import.Type), getStream());
673 encodeULEB128(0, getStream()); // mutability
676 llvm_unreachable("unsupported import kind");
683 void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
684 if (Functions.empty())
687 SectionBookkeeping Section;
688 startSection(Section, wasm::WASM_SEC_FUNCTION);
690 encodeULEB128(Functions.size(), getStream());
691 for (const WasmFunction &Func : Functions)
692 encodeULEB128(Func.Type, getStream());
697 void WasmObjectWriter::writeTableSection(uint32_t NumElements) {
698 // For now, always emit the table section, since indirect calls are not
699 // valid without it. In the future, we could perhaps be more clever and omit
700 // it if there are no indirect calls.
702 SectionBookkeeping Section;
703 startSection(Section, wasm::WASM_SEC_TABLE);
705 encodeULEB128(1, getStream()); // The number of tables.
706 // Fixed to 1 for now.
707 encodeSLEB128(wasm::WASM_TYPE_ANYFUNC, getStream()); // Type of table
708 encodeULEB128(0, getStream()); // flags
709 encodeULEB128(NumElements, getStream()); // initial
714 void WasmObjectWriter::writeMemorySection(uint32_t DataSize) {
715 // For now, always emit the memory section, since loads and stores are not
716 // valid without it. In the future, we could perhaps be more clever and omit
717 // it if there are no loads or stores.
718 SectionBookkeeping Section;
719 uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
721 startSection(Section, wasm::WASM_SEC_MEMORY);
722 encodeULEB128(1, getStream()); // number of memory spaces
724 encodeULEB128(0, getStream()); // flags
725 encodeULEB128(NumPages, getStream()); // initial
730 void WasmObjectWriter::writeGlobalSection() {
734 SectionBookkeeping Section;
735 startSection(Section, wasm::WASM_SEC_GLOBAL);
737 encodeULEB128(Globals.size(), getStream());
738 for (const WasmGlobal &Global : Globals) {
739 writeValueType(Global.Type);
740 write8(Global.IsMutable);
742 if (Global.HasImport) {
743 assert(Global.InitialValue == 0);
744 write8(wasm::WASM_OPCODE_GET_GLOBAL);
745 encodeULEB128(Global.ImportIndex, getStream());
747 assert(Global.ImportIndex == 0);
748 write8(wasm::WASM_OPCODE_I32_CONST);
749 encodeSLEB128(Global.InitialValue, getStream()); // offset
751 write8(wasm::WASM_OPCODE_END);
757 void WasmObjectWriter::writeExportSection(ArrayRef<WasmExport> Exports) {
761 SectionBookkeeping Section;
762 startSection(Section, wasm::WASM_SEC_EXPORT);
764 encodeULEB128(Exports.size(), getStream());
765 for (const WasmExport &Export : Exports) {
766 writeString(Export.FieldName);
767 encodeSLEB128(Export.Kind, getStream());
768 encodeULEB128(Export.Index, getStream());
774 void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
775 if (TableElems.empty())
778 SectionBookkeeping Section;
779 startSection(Section, wasm::WASM_SEC_ELEM);
781 encodeULEB128(1, getStream()); // number of "segments"
782 encodeULEB128(0, getStream()); // the table index
784 // init expr for starting offset
785 write8(wasm::WASM_OPCODE_I32_CONST);
786 encodeSLEB128(0, getStream());
787 write8(wasm::WASM_OPCODE_END);
789 encodeULEB128(TableElems.size(), getStream());
790 for (uint32_t Elem : TableElems)
791 encodeULEB128(Elem, getStream());
796 void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
797 const MCAsmLayout &Layout,
798 ArrayRef<WasmFunction> Functions) {
799 if (Functions.empty())
802 SectionBookkeeping Section;
803 startSection(Section, wasm::WASM_SEC_CODE);
805 encodeULEB128(Functions.size(), getStream());
807 for (const WasmFunction &Func : Functions) {
808 auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
811 if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
812 report_fatal_error(".size expression must be evaluatable");
814 encodeULEB128(Size, getStream());
815 FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset);
816 Asm.writeSectionData(&FuncSection, Layout);
820 applyRelocations(CodeRelocations, Section.ContentsOffset);
825 void WasmObjectWriter::writeDataSection(ArrayRef<WasmDataSegment> Segments) {
826 if (Segments.empty())
829 SectionBookkeeping Section;
830 startSection(Section, wasm::WASM_SEC_DATA);
832 encodeULEB128(Segments.size(), getStream()); // count
834 for (const WasmDataSegment & Segment : Segments) {
835 encodeULEB128(0, getStream()); // memory index
836 write8(wasm::WASM_OPCODE_I32_CONST);
837 encodeSLEB128(Segment.Offset, getStream()); // offset
838 write8(wasm::WASM_OPCODE_END);
839 encodeULEB128(Segment.Data.size(), getStream()); // size
840 Segment.Section->setSectionOffset(getStream().tell() - Section.ContentsOffset);
841 writeBytes(Segment.Data); // data
845 applyRelocations(DataRelocations, Section.ContentsOffset);
850 void WasmObjectWriter::writeNameSection(
851 ArrayRef<WasmFunction> Functions,
852 ArrayRef<WasmImport> Imports,
853 unsigned NumFuncImports) {
854 uint32_t TotalFunctions = NumFuncImports + Functions.size();
855 if (TotalFunctions == 0)
858 SectionBookkeeping Section;
859 startSection(Section, wasm::WASM_SEC_CUSTOM, "name");
860 SectionBookkeeping SubSection;
861 startSection(SubSection, wasm::WASM_NAMES_FUNCTION);
863 encodeULEB128(TotalFunctions, getStream());
865 for (const WasmImport &Import : Imports) {
866 if (Import.Kind == wasm::WASM_EXTERNAL_FUNCTION) {
867 encodeULEB128(Index, getStream());
868 writeString(Import.FieldName);
872 for (const WasmFunction &Func : Functions) {
873 encodeULEB128(Index, getStream());
874 writeString(Func.Sym->getName());
878 endSection(SubSection);
882 void WasmObjectWriter::writeCodeRelocSection() {
883 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
884 // for descriptions of the reloc sections.
886 if (CodeRelocations.empty())
889 SectionBookkeeping Section;
890 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.CODE");
892 encodeULEB128(wasm::WASM_SEC_CODE, getStream());
893 encodeULEB128(CodeRelocations.size(), getStream());
895 writeRelocations(CodeRelocations);
900 void WasmObjectWriter::writeDataRelocSection() {
901 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
902 // for descriptions of the reloc sections.
904 if (DataRelocations.empty())
907 SectionBookkeeping Section;
908 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.DATA");
910 encodeULEB128(wasm::WASM_SEC_DATA, getStream());
911 encodeULEB128(DataRelocations.size(), getStream());
913 writeRelocations(DataRelocations);
918 void WasmObjectWriter::writeLinkingMetaDataSection(
919 ArrayRef<WasmDataSegment> Segments, uint32_t DataSize,
920 SmallVector<std::pair<StringRef, uint32_t>, 4> SymbolFlags,
921 bool HasStackPointer, uint32_t StackPointerGlobal) {
922 SectionBookkeeping Section;
923 startSection(Section, wasm::WASM_SEC_CUSTOM, "linking");
924 SectionBookkeeping SubSection;
926 if (HasStackPointer) {
927 startSection(SubSection, wasm::WASM_STACK_POINTER);
928 encodeULEB128(StackPointerGlobal, getStream()); // id
929 endSection(SubSection);
932 if (SymbolFlags.size() != 0) {
933 startSection(SubSection, wasm::WASM_SYMBOL_INFO);
934 encodeULEB128(SymbolFlags.size(), getStream());
935 for (auto Pair: SymbolFlags) {
936 writeString(Pair.first);
937 encodeULEB128(Pair.second, getStream());
939 endSection(SubSection);
943 startSection(SubSection, wasm::WASM_DATA_SIZE);
944 encodeULEB128(DataSize, getStream());
945 endSection(SubSection);
948 if (Segments.size()) {
949 startSection(SubSection, wasm::WASM_SEGMENT_INFO);
950 encodeULEB128(Segments.size(), getStream());
951 for (const WasmDataSegment &Segment : Segments) {
952 writeString(Segment.Name);
953 encodeULEB128(Segment.Alignment, getStream());
954 encodeULEB128(Segment.Flags, getStream());
956 endSection(SubSection);
962 uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm& Symbol) {
963 assert(Symbol.isFunction());
964 assert(TypeIndices.count(&Symbol));
965 return TypeIndices[&Symbol];
968 uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm& Symbol) {
969 assert(Symbol.isFunction());
972 const MCSymbolWasm* ResolvedSym = ResolveSymbol(Symbol);
973 F.Returns = ResolvedSym->getReturns();
974 F.Params = ResolvedSym->getParams();
977 FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
979 FunctionTypes.push_back(F);
980 TypeIndices[&Symbol] = Pair.first->second;
982 DEBUG(dbgs() << "registerFunctionType: " << Symbol << " new:" << Pair.second << "\n");
983 DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n");
984 return Pair.first->second;
987 void WasmObjectWriter::writeObject(MCAssembler &Asm,
988 const MCAsmLayout &Layout) {
989 DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
990 MCContext &Ctx = Asm.getContext();
991 wasm::ValType PtrType = is64Bit() ? wasm::ValType::I64 : wasm::ValType::I32;
993 // Collect information from the available symbols.
994 SmallVector<WasmFunction, 4> Functions;
995 SmallVector<uint32_t, 4> TableElems;
996 SmallVector<WasmImport, 4> Imports;
997 SmallVector<WasmExport, 4> Exports;
998 SmallVector<std::pair<StringRef, uint32_t>, 4> SymbolFlags;
999 SmallPtrSet<const MCSymbolWasm *, 4> IsAddressTaken;
1000 unsigned NumFuncImports = 0;
1001 SmallVector<WasmDataSegment, 4> DataSegments;
1002 uint32_t StackPointerGlobal = 0;
1003 uint32_t DataSize = 0;
1004 bool HasStackPointer = false;
1006 // Populate the IsAddressTaken set.
1007 for (const WasmRelocationEntry &RelEntry : CodeRelocations) {
1008 switch (RelEntry.Type) {
1009 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
1010 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
1011 IsAddressTaken.insert(RelEntry.Symbol);
1017 for (const WasmRelocationEntry &RelEntry : DataRelocations) {
1018 switch (RelEntry.Type) {
1019 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
1020 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
1021 IsAddressTaken.insert(RelEntry.Symbol);
1028 // Populate FunctionTypeIndices and Imports.
1029 for (const MCSymbol &S : Asm.symbols()) {
1030 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1032 if (WS.isTemporary())
1035 if (WS.isFunction())
1036 registerFunctionType(WS);
1038 // If the symbol is not defined in this translation unit, import it.
1039 if (!WS.isDefined(/*SetUsed=*/false)) {
1041 Import.ModuleName = WS.getModuleName();
1042 Import.FieldName = WS.getName();
1044 if (WS.isFunction()) {
1045 Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1046 Import.Type = getFunctionType(WS);
1047 SymbolIndices[&WS] = NumFuncImports;
1050 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1051 Import.Type = int32_t(PtrType);
1052 SymbolIndices[&WS] = NumGlobalImports;
1056 Imports.push_back(Import);
1060 // In the special .global_variables section, we've encoded global
1061 // variables used by the function. Translate them into the Globals
1063 MCSectionWasm *GlobalVars = Ctx.getWasmSection(".global_variables", wasm::WASM_SEC_DATA);
1064 if (!GlobalVars->getFragmentList().empty()) {
1065 if (GlobalVars->getFragmentList().size() != 1)
1066 report_fatal_error("only one .global_variables fragment supported");
1067 const MCFragment &Frag = *GlobalVars->begin();
1068 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1069 report_fatal_error("only data supported in .global_variables");
1070 const auto &DataFrag = cast<MCDataFragment>(Frag);
1071 if (!DataFrag.getFixups().empty())
1072 report_fatal_error("fixups not supported in .global_variables");
1073 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1074 for (const uint8_t *p = (const uint8_t *)Contents.data(),
1075 *end = (const uint8_t *)Contents.data() + Contents.size();
1079 report_fatal_error("truncated global variable encoding");
1080 G.Type = wasm::ValType(int8_t(*p++));
1081 G.IsMutable = bool(*p++);
1082 G.HasImport = bool(*p++);
1087 Import.ModuleName = (const char *)p;
1088 const uint8_t *nul = (const uint8_t *)memchr(p, '\0', end - p);
1090 report_fatal_error("global module name must be nul-terminated");
1092 nul = (const uint8_t *)memchr(p, '\0', end - p);
1094 report_fatal_error("global base name must be nul-terminated");
1095 Import.FieldName = (const char *)p;
1098 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1099 Import.Type = int32_t(G.Type);
1101 G.ImportIndex = NumGlobalImports;
1104 Imports.push_back(Import);
1107 G.InitialValue = decodeSLEB128(p, &n);
1109 if ((ptrdiff_t)n > end - p)
1110 report_fatal_error("global initial value must be valid SLEB128");
1113 Globals.push_back(G);
1117 // In the special .stack_pointer section, we've encoded the stack pointer
1119 MCSectionWasm *StackPtr = Ctx.getWasmSection(".stack_pointer", wasm::WASM_SEC_DATA);
1120 if (!StackPtr->getFragmentList().empty()) {
1121 if (StackPtr->getFragmentList().size() != 1)
1122 report_fatal_error("only one .stack_pointer fragment supported");
1123 const MCFragment &Frag = *StackPtr->begin();
1124 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1125 report_fatal_error("only data supported in .stack_pointer");
1126 const auto &DataFrag = cast<MCDataFragment>(Frag);
1127 if (!DataFrag.getFixups().empty())
1128 report_fatal_error("fixups not supported in .stack_pointer");
1129 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1130 if (Contents.size() != 4)
1131 report_fatal_error("only one entry supported in .stack_pointer");
1132 HasStackPointer = true;
1133 StackPointerGlobal = NumGlobalImports + *(const int32_t *)Contents.data();
1136 for (MCSection &Sec : Asm) {
1137 auto &Section = static_cast<MCSectionWasm &>(Sec);
1138 if (Section.getType() != wasm::WASM_SEC_DATA)
1141 DataSize = alignTo(DataSize, Section.getAlignment());
1142 DataSegments.emplace_back();
1143 WasmDataSegment &Segment = DataSegments.back();
1144 Segment.Name = Section.getSectionName();
1145 Segment.Offset = DataSize;
1146 Segment.Section = &Section;
1147 addData(Segment.Data, Section);
1148 Segment.Alignment = Section.getAlignment();
1150 DataSize += Segment.Data.size();
1151 Section.setMemoryOffset(Segment.Offset);
1154 // Handle regular defined and undefined symbols.
1155 for (const MCSymbol &S : Asm.symbols()) {
1156 // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1157 // or used in relocations.
1158 if (S.isTemporary() && S.getName().empty())
1161 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1162 DEBUG(dbgs() << "MCSymbol: '" << S << "'"
1163 << " isDefined=" << S.isDefined() << " isExternal="
1164 << S.isExternal() << " isTemporary=" << S.isTemporary()
1165 << " isFunction=" << WS.isFunction()
1166 << " isWeak=" << WS.isWeak()
1167 << " isVariable=" << WS.isVariable() << "\n");
1170 SymbolFlags.emplace_back(WS.getName(), wasm::WASM_SYMBOL_BINDING_WEAK);
1172 if (WS.isVariable())
1177 if (WS.isFunction()) {
1178 if (WS.isDefined(/*SetUsed=*/false)) {
1179 if (WS.getOffset() != 0)
1181 "function sections must contain one function each");
1183 if (WS.getSize() == 0)
1185 "function symbols must have a size set with .size");
1187 // A definition. Take the next available index.
1188 Index = NumFuncImports + Functions.size();
1190 // Prepare the function.
1192 Func.Type = getFunctionType(WS);
1194 SymbolIndices[&WS] = Index;
1195 Functions.push_back(Func);
1197 // An import; the index was assigned above.
1198 Index = SymbolIndices.find(&WS)->second;
1201 DEBUG(dbgs() << " -> function index: " << Index << "\n");
1203 // If needed, prepare the function to be called indirectly.
1204 if (IsAddressTaken.count(&WS) != 0) {
1205 IndirectSymbolIndices[&WS] = TableElems.size();
1206 DEBUG(dbgs() << " -> adding to table: " << TableElems.size() << "\n");
1207 TableElems.push_back(Index);
1210 if (WS.isTemporary() && !WS.getSize())
1213 if (!WS.isDefined(/*SetUsed=*/false))
1217 report_fatal_error("data symbols must have a size set with .size: " +
1221 if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1222 report_fatal_error(".size expression must be evaluatable");
1224 // For each global, prepare a corresponding wasm global holding its
1225 // address. For externals these will also be named exports.
1226 Index = NumGlobalImports + Globals.size();
1227 auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1230 Global.Type = PtrType;
1231 Global.IsMutable = false;
1232 Global.HasImport = false;
1233 Global.InitialValue = DataSection.getMemoryOffset() + Layout.getSymbolOffset(WS);
1234 Global.ImportIndex = 0;
1235 SymbolIndices[&WS] = Index;
1236 DEBUG(dbgs() << " -> global index: " << Index << "\n");
1237 Globals.push_back(Global);
1240 // If the symbol is visible outside this translation unit, export it.
1241 if (WS.isDefined(/*SetUsed=*/false)) {
1243 Export.FieldName = WS.getName();
1244 Export.Index = Index;
1245 if (WS.isFunction())
1246 Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1248 Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1249 DEBUG(dbgs() << " -> export " << Exports.size() << "\n");
1250 Exports.push_back(Export);
1251 if (!WS.isExternal())
1252 SymbolFlags.emplace_back(WS.getName(), wasm::WASM_SYMBOL_BINDING_LOCAL);
1256 // Handle weak aliases. We need to process these in a separate pass because
1257 // we need to have processed the target of the alias before the alias itself
1258 // and the symbols are not necessarily ordered in this way.
1259 for (const MCSymbol &S : Asm.symbols()) {
1260 if (!S.isVariable())
1263 assert(S.isDefined(/*SetUsed=*/false));
1265 // Find the target symbol of this weak alias and export that index
1266 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1267 const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS);
1268 DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym << "'\n");
1269 assert(SymbolIndices.count(ResolvedSym) > 0);
1270 uint32_t Index = SymbolIndices.find(ResolvedSym)->second;
1271 DEBUG(dbgs() << " -> index:" << Index << "\n");
1273 SymbolIndices[&WS] = Index;
1275 Export.FieldName = WS.getName();
1276 Export.Index = Index;
1277 if (WS.isFunction())
1278 Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1280 Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1281 DEBUG(dbgs() << " -> export " << Exports.size() << "\n");
1282 Exports.push_back(Export);
1284 if (!WS.isExternal())
1285 SymbolFlags.emplace_back(WS.getName(), wasm::WASM_SYMBOL_BINDING_LOCAL);
1288 // Add types for indirect function calls.
1289 for (const WasmRelocationEntry &Fixup : CodeRelocations) {
1290 if (Fixup.Type != wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB)
1293 registerFunctionType(*Fixup.Symbol);
1296 // Write out the Wasm header.
1299 writeTypeSection(FunctionTypes);
1300 writeImportSection(Imports);
1301 writeFunctionSection(Functions);
1302 writeTableSection(TableElems.size());
1303 writeMemorySection(DataSize);
1304 writeGlobalSection();
1305 writeExportSection(Exports);
1306 // TODO: Start Section
1307 writeElemSection(TableElems);
1308 writeCodeSection(Asm, Layout, Functions);
1309 writeDataSection(DataSegments);
1310 writeNameSection(Functions, Imports, NumFuncImports);
1311 writeCodeRelocSection();
1312 writeDataRelocSection();
1313 writeLinkingMetaDataSection(DataSegments, DataSize, SymbolFlags,
1314 HasStackPointer, StackPointerGlobal);
1316 // TODO: Translate the .comment section to the output.
1317 // TODO: Translate debug sections to the output.
1320 std::unique_ptr<MCObjectWriter>
1321 llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1322 raw_pwrite_stream &OS) {
1323 // FIXME: Can't use make_unique<WasmObjectWriter>(...) as WasmObjectWriter's
1324 // destructor is private. Is that necessary?
1325 return std::unique_ptr<MCObjectWriter>(
1326 new WasmObjectWriter(std::move(MOTW), OS));