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