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