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