Bug Summary

File:llvm/lib/MC/WasmObjectWriter.cpp
Warning:line 1565, column 11
Value stored to 'Index' is never read

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name WasmObjectWriter.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/lib/MC -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/lib/MC -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/llvm/lib/MC -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/llvm/include -D NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/lib/MC -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-09-04-040900-46481-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/llvm/lib/MC/WasmObjectWriter.cpp
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
37using namespace llvm;
38
39#define DEBUG_TYPE"mc" "mc"
40
41namespace {
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.
45static 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.
50struct 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.
64struct 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.
75struct WasmFunction {
76 uint32_t SigIndex;
77 const MCSymbolWasm *Sym;
78};
79
80// A wasm global to be written into the global section.
81struct 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.
89struct WasmComdatEntry {
90 unsigned Kind;
91 uint32_t Index;
92};
93
94// Information about a single relocation.
95struct 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
102 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
108 bool hasAddend() const { return wasm::relocTypeHasAddend(Type); }
109
110 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(NDEBUG1) || defined(LLVM_ENABLE_DUMP)
117 LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void dump() const { print(dbgs()); }
118#endif
119};
120
121static const uint32_t InvalidIndex = -1;
122
123struct WasmCustomSection {
124
125 StringRef Name;
126 MCSectionWasm *Section;
127
128 uint32_t OutputContentsOffset;
129 uint32_t OutputIndex;
130
131 WasmCustomSection(StringRef Name, MCSectionWasm *Section)
132 : Name(Name), Section(Section), OutputContentsOffset(0),
133 OutputIndex(InvalidIndex) {}
134};
135
136#if !defined(NDEBUG1)
137raw_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.
145template <int W>
146void 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)(static_cast<void> (0));
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.
155template <int W>
156void 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)(static_cast<void> (0));
160 Stream.pwrite((char *)Buffer, SizeLen, Offset);
161}
162
163// Write X as a plain integer value at offset Offset in Stream.
164static 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
170static 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
176bool isDwoSection(const MCSection &Sec) {
177 return Sec.getName().endswith(".dwo");
178}
179
180class 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/tag/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 NumTagImports = 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.
235 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
236 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
242public:
243 WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
244 raw_pwrite_stream &OS_)
245 : TargetObjectWriter(std::move(MOTW)), OS(&OS_) {}
246
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
252private:
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
290 void writeString(const StringRef Str) {
291 encodeULEB128(Str.size(), W->OS);
292 W->OS << Str;
293 }
294
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
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
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 writeTagSection(ArrayRef<wasm::WasmTagType> Tags);
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 getTagType(const MCSymbolWasm &Symbol);
341 void registerFunctionType(const MCSymbolWasm &Symbol);
342 void registerTagType(const MCSymbolWasm &Symbol);
343};
344
345} // end anonymous namespace
346
347// Write out a section header and a patchable section size field.
348void WasmObjectWriter::startSection(SectionBookkeeping &Section,
349 unsigned SectionId) {
350 LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n")do { } while (false);
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
365void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
366 StringRef Name) {
367 LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n")do { } while (false);
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.
382void 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")do { } while (false);
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.
402void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
403 W->OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
404 W->write<uint32_t>(wasm::WasmVersion);
405}
406
407void 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
435void 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 &(static_cast<void> (0))
442 MCFixupKindInfo::FKF_IsPCRel))(static_cast<void> (0));
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")__builtin_unreachable();
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 =
502 TargetObjectWriter->getRelocType(Target, Fixup, FixupSection, IsLocRel);
503
504 // Absolute offset within a section or a function.
505 // Currently only supported for for metadata sections.
506 // See: test/MC/WebAssembly/blockaddress.ll
507 if ((Type == wasm::R_WASM_FUNCTION_OFFSET_I32 ||
508 Type == wasm::R_WASM_FUNCTION_OFFSET_I64 ||
509 Type == wasm::R_WASM_SECTION_OFFSET_I32) &&
510 SymA->isDefined()) {
511 // SymA can be a temp data symbol that represents a function (in which case
512 // it needs to be replaced by the section symbol), [XXX and it apparently
513 // later gets changed again to a func symbol?] or it can be a real
514 // function symbol, in which case it can be left as-is.
515
516 if (!FixupSection.getKind().isMetadata())
517 report_fatal_error("relocations for function or section offsets are "
518 "only supported in metadata sections");
519
520 const MCSymbol *SectionSymbol = nullptr;
521 const MCSection &SecA = SymA->getSection();
522 if (SecA.getKind().isText()) {
523 auto SecSymIt = SectionFunctions.find(&SecA);
524 if (SecSymIt == SectionFunctions.end())
525 report_fatal_error("section doesn\'t have defining symbol");
526 SectionSymbol = SecSymIt->second;
527 } else {
528 SectionSymbol = SecA.getBeginSymbol();
529 }
530 if (!SectionSymbol)
531 report_fatal_error("section symbol is required for relocation");
532
533 C += Layout.getSymbolOffset(*SymA);
534 SymA = cast<MCSymbolWasm>(SectionSymbol);
535 }
536
537 if (Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB ||
538 Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB64 ||
539 Type == wasm::R_WASM_TABLE_INDEX_SLEB ||
540 Type == wasm::R_WASM_TABLE_INDEX_SLEB64 ||
541 Type == wasm::R_WASM_TABLE_INDEX_I32 ||
542 Type == wasm::R_WASM_TABLE_INDEX_I64) {
543 // TABLE_INDEX relocs implicitly use the default indirect function table.
544 // We require the function table to have already been defined.
545 auto TableName = "__indirect_function_table";
546 MCSymbolWasm *Sym = cast_or_null<MCSymbolWasm>(Ctx.lookupSymbol(TableName));
547 if (!Sym) {
548 report_fatal_error("missing indirect function table symbol");
549 } else {
550 if (!Sym->isFunctionTable())
551 report_fatal_error("__indirect_function_table symbol has wrong type");
552 // Ensure that __indirect_function_table reaches the output.
553 Sym->setNoStrip();
554 Asm.registerSymbol(*Sym);
555 }
556 }
557
558 // Relocation other than R_WASM_TYPE_INDEX_LEB are required to be
559 // against a named symbol.
560 if (Type != wasm::R_WASM_TYPE_INDEX_LEB) {
561 if (SymA->getName().empty())
562 report_fatal_error("relocations against un-named temporaries are not yet "
563 "supported by wasm");
564
565 SymA->setUsedInReloc();
566 }
567
568 if (RefA->getKind() == MCSymbolRefExpr::VK_GOT)
569 SymA->setUsedInGOT();
570
571 WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
572 LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n")do { } while (false);
573
574 if (FixupSection.isWasmData()) {
575 DataRelocations.push_back(Rec);
576 } else if (FixupSection.getKind().isText()) {
577 CodeRelocations.push_back(Rec);
578 } else if (FixupSection.getKind().isMetadata()) {
579 CustomSectionsRelocations[&FixupSection].push_back(Rec);
580 } else {
581 llvm_unreachable("unexpected section type")__builtin_unreachable();
582 }
583}
584
585// Compute a value to write into the code at the location covered
586// by RelEntry. This value isn't used by the static linker; it just serves
587// to make the object format more readable and more likely to be directly
588// useable.
589uint64_t
590WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry,
591 const MCAsmLayout &Layout) {
592 if ((RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_LEB ||
593 RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_I32) &&
594 !RelEntry.Symbol->isGlobal()) {
595 assert(GOTIndices.count(RelEntry.Symbol) > 0 && "symbol not found in GOT index space")(static_cast<void> (0));
596 return GOTIndices[RelEntry.Symbol];
597 }
598
599 switch (RelEntry.Type) {
600 case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
601 case wasm::R_WASM_TABLE_INDEX_REL_SLEB64:
602 case wasm::R_WASM_TABLE_INDEX_SLEB:
603 case wasm::R_WASM_TABLE_INDEX_SLEB64:
604 case wasm::R_WASM_TABLE_INDEX_I32:
605 case wasm::R_WASM_TABLE_INDEX_I64: {
606 // Provisional value is table address of the resolved symbol itself
607 const MCSymbolWasm *Base =
608 cast<MCSymbolWasm>(Layout.getBaseSymbol(*RelEntry.Symbol));
609 assert(Base->isFunction())(static_cast<void> (0));
610 if (RelEntry.Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB ||
611 RelEntry.Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB64)
612 return TableIndices[Base] - InitialTableOffset;
613 else
614 return TableIndices[Base];
615 }
616 case wasm::R_WASM_TYPE_INDEX_LEB:
617 // Provisional value is same as the index
618 return getRelocationIndexValue(RelEntry);
619 case wasm::R_WASM_FUNCTION_INDEX_LEB:
620 case wasm::R_WASM_GLOBAL_INDEX_LEB:
621 case wasm::R_WASM_GLOBAL_INDEX_I32:
622 case wasm::R_WASM_TAG_INDEX_LEB:
623 case wasm::R_WASM_TABLE_NUMBER_LEB:
624 // Provisional value is function/global/tag Wasm index
625 assert(WasmIndices.count(RelEntry.Symbol) > 0 && "symbol not found in wasm index space")(static_cast<void> (0));
626 return WasmIndices[RelEntry.Symbol];
627 case wasm::R_WASM_FUNCTION_OFFSET_I32:
628 case wasm::R_WASM_FUNCTION_OFFSET_I64:
629 case wasm::R_WASM_SECTION_OFFSET_I32: {
630 if (!RelEntry.Symbol->isDefined())
631 return 0;
632 const auto &Section =
633 static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
634 return Section.getSectionOffset() + RelEntry.Addend;
635 }
636 case wasm::R_WASM_MEMORY_ADDR_LEB:
637 case wasm::R_WASM_MEMORY_ADDR_LEB64:
638 case wasm::R_WASM_MEMORY_ADDR_SLEB:
639 case wasm::R_WASM_MEMORY_ADDR_SLEB64:
640 case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
641 case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
642 case wasm::R_WASM_MEMORY_ADDR_I32:
643 case wasm::R_WASM_MEMORY_ADDR_I64:
644 case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB:
645 case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB64:
646 case wasm::R_WASM_MEMORY_ADDR_LOCREL_I32: {
647 // Provisional value is address of the global plus the offset
648 // For undefined symbols, use zero
649 if (!RelEntry.Symbol->isDefined())
650 return 0;
651 const wasm::WasmDataReference &SymRef = DataLocations[RelEntry.Symbol];
652 const WasmDataSegment &Segment = DataSegments[SymRef.Segment];
653 // Ignore overflow. LLVM allows address arithmetic to silently wrap.
654 return Segment.Offset + SymRef.Offset + RelEntry.Addend;
655 }
656 default:
657 llvm_unreachable("invalid relocation type")__builtin_unreachable();
658 }
659}
660
661static void addData(SmallVectorImpl<char> &DataBytes,
662 MCSectionWasm &DataSection) {
663 LLVM_DEBUG(errs() << "addData: " << DataSection.getName() << "\n")do { } while (false);
664
665 DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
666
667 for (const MCFragment &Frag : DataSection) {
668 if (Frag.hasInstructions())
669 report_fatal_error("only data supported in data sections");
670
671 if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
672 if (Align->getValueSize() != 1)
673 report_fatal_error("only byte values supported for alignment");
674 // If nops are requested, use zeros, as this is the data section.
675 uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
676 uint64_t Size =
677 std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
678 DataBytes.size() + Align->getMaxBytesToEmit());
679 DataBytes.resize(Size, Value);
680 } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
681 int64_t NumValues;
682 if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
683 llvm_unreachable("The fill should be an assembler constant")__builtin_unreachable();
684 DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
685 Fill->getValue());
686 } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) {
687 const SmallVectorImpl<char> &Contents = LEB->getContents();
688 llvm::append_range(DataBytes, Contents);
689 } else {
690 const auto &DataFrag = cast<MCDataFragment>(Frag);
691 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
692 llvm::append_range(DataBytes, Contents);
693 }
694 }
695
696 LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n")do { } while (false);
697}
698
699uint32_t
700WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
701 if (RelEntry.Type == wasm::R_WASM_TYPE_INDEX_LEB) {
702 if (!TypeIndices.count(RelEntry.Symbol))
703 report_fatal_error("symbol not found in type index space: " +
704 RelEntry.Symbol->getName());
705 return TypeIndices[RelEntry.Symbol];
706 }
707
708 return RelEntry.Symbol->getIndex();
709}
710
711// Apply the portions of the relocation records that we can handle ourselves
712// directly.
713void WasmObjectWriter::applyRelocations(
714 ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset,
715 const MCAsmLayout &Layout) {
716 auto &Stream = static_cast<raw_pwrite_stream &>(W->OS);
717 for (const WasmRelocationEntry &RelEntry : Relocations) {
718 uint64_t Offset = ContentsOffset +
719 RelEntry.FixupSection->getSectionOffset() +
720 RelEntry.Offset;
721
722 LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n")do { } while (false);
723 auto Value = getProvisionalValue(RelEntry, Layout);
724
725 switch (RelEntry.Type) {
726 case wasm::R_WASM_FUNCTION_INDEX_LEB:
727 case wasm::R_WASM_TYPE_INDEX_LEB:
728 case wasm::R_WASM_GLOBAL_INDEX_LEB:
729 case wasm::R_WASM_MEMORY_ADDR_LEB:
730 case wasm::R_WASM_TAG_INDEX_LEB:
731 case wasm::R_WASM_TABLE_NUMBER_LEB:
732 writePatchableLEB<5>(Stream, Value, Offset);
733 break;
734 case wasm::R_WASM_MEMORY_ADDR_LEB64:
735 writePatchableLEB<10>(Stream, Value, Offset);
736 break;
737 case wasm::R_WASM_TABLE_INDEX_I32:
738 case wasm::R_WASM_MEMORY_ADDR_I32:
739 case wasm::R_WASM_FUNCTION_OFFSET_I32:
740 case wasm::R_WASM_SECTION_OFFSET_I32:
741 case wasm::R_WASM_GLOBAL_INDEX_I32:
742 case wasm::R_WASM_MEMORY_ADDR_LOCREL_I32:
743 patchI32(Stream, Value, Offset);
744 break;
745 case wasm::R_WASM_TABLE_INDEX_I64:
746 case wasm::R_WASM_MEMORY_ADDR_I64:
747 case wasm::R_WASM_FUNCTION_OFFSET_I64:
748 patchI64(Stream, Value, Offset);
749 break;
750 case wasm::R_WASM_TABLE_INDEX_SLEB:
751 case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
752 case wasm::R_WASM_MEMORY_ADDR_SLEB:
753 case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
754 case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB:
755 writePatchableSLEB<5>(Stream, Value, Offset);
756 break;
757 case wasm::R_WASM_TABLE_INDEX_SLEB64:
758 case wasm::R_WASM_TABLE_INDEX_REL_SLEB64:
759 case wasm::R_WASM_MEMORY_ADDR_SLEB64:
760 case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
761 case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB64:
762 writePatchableSLEB<10>(Stream, Value, Offset);
763 break;
764 default:
765 llvm_unreachable("invalid relocation type")__builtin_unreachable();
766 }
767 }
768}
769
770void WasmObjectWriter::writeTypeSection(
771 ArrayRef<wasm::WasmSignature> Signatures) {
772 if (Signatures.empty())
773 return;
774
775 SectionBookkeeping Section;
776 startSection(Section, wasm::WASM_SEC_TYPE);
777
778 encodeULEB128(Signatures.size(), W->OS);
779
780 for (const wasm::WasmSignature &Sig : Signatures) {
781 W->OS << char(wasm::WASM_TYPE_FUNC);
782 encodeULEB128(Sig.Params.size(), W->OS);
783 for (wasm::ValType Ty : Sig.Params)
784 writeValueType(Ty);
785 encodeULEB128(Sig.Returns.size(), W->OS);
786 for (wasm::ValType Ty : Sig.Returns)
787 writeValueType(Ty);
788 }
789
790 endSection(Section);
791}
792
793void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
794 uint64_t DataSize,
795 uint32_t NumElements) {
796 if (Imports.empty())
797 return;
798
799 uint64_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
800
801 SectionBookkeeping Section;
802 startSection(Section, wasm::WASM_SEC_IMPORT);
803
804 encodeULEB128(Imports.size(), W->OS);
805 for (const wasm::WasmImport &Import : Imports) {
806 writeString(Import.Module);
807 writeString(Import.Field);
808 W->OS << char(Import.Kind);
809
810 switch (Import.Kind) {
811 case wasm::WASM_EXTERNAL_FUNCTION:
812 encodeULEB128(Import.SigIndex, W->OS);
813 break;
814 case wasm::WASM_EXTERNAL_GLOBAL:
815 W->OS << char(Import.Global.Type);
816 W->OS << char(Import.Global.Mutable ? 1 : 0);
817 break;
818 case wasm::WASM_EXTERNAL_MEMORY:
819 encodeULEB128(Import.Memory.Flags, W->OS);
820 encodeULEB128(NumPages, W->OS); // initial
821 break;
822 case wasm::WASM_EXTERNAL_TABLE:
823 W->OS << char(Import.Table.ElemType);
824 encodeULEB128(0, W->OS); // flags
825 encodeULEB128(NumElements, W->OS); // initial
826 break;
827 case wasm::WASM_EXTERNAL_TAG:
828 W->OS << char(Import.Tag.Attribute);
829 encodeULEB128(Import.Tag.SigIndex, W->OS);
830 break;
831 default:
832 llvm_unreachable("unsupported import kind")__builtin_unreachable();
833 }
834 }
835
836 endSection(Section);
837}
838
839void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
840 if (Functions.empty())
841 return;
842
843 SectionBookkeeping Section;
844 startSection(Section, wasm::WASM_SEC_FUNCTION);
845
846 encodeULEB128(Functions.size(), W->OS);
847 for (const WasmFunction &Func : Functions)
848 encodeULEB128(Func.SigIndex, W->OS);
849
850 endSection(Section);
851}
852
853void WasmObjectWriter::writeTagSection(ArrayRef<wasm::WasmTagType> Tags) {
854 if (Tags.empty())
855 return;
856
857 SectionBookkeeping Section;
858 startSection(Section, wasm::WASM_SEC_TAG);
859
860 encodeULEB128(Tags.size(), W->OS);
861 for (const wasm::WasmTagType &Tag : Tags) {
862 W->OS << char(Tag.Attribute);
863 encodeULEB128(Tag.SigIndex, W->OS);
864 }
865
866 endSection(Section);
867}
868
869void WasmObjectWriter::writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals) {
870 if (Globals.empty())
871 return;
872
873 SectionBookkeeping Section;
874 startSection(Section, wasm::WASM_SEC_GLOBAL);
875
876 encodeULEB128(Globals.size(), W->OS);
877 for (const wasm::WasmGlobal &Global : Globals) {
878 encodeULEB128(Global.Type.Type, W->OS);
879 W->OS << char(Global.Type.Mutable);
880 W->OS << char(Global.InitExpr.Opcode);
881 switch (Global.Type.Type) {
882 case wasm::WASM_TYPE_I32:
883 encodeSLEB128(0, W->OS);
884 break;
885 case wasm::WASM_TYPE_I64:
886 encodeSLEB128(0, W->OS);
887 break;
888 case wasm::WASM_TYPE_F32:
889 writeI32(0);
890 break;
891 case wasm::WASM_TYPE_F64:
892 writeI64(0);
893 break;
894 case wasm::WASM_TYPE_EXTERNREF:
895 writeValueType(wasm::ValType::EXTERNREF);
896 break;
897 default:
898 llvm_unreachable("unexpected type")__builtin_unreachable();
899 }
900 W->OS << char(wasm::WASM_OPCODE_END);
901 }
902
903 endSection(Section);
904}
905
906void WasmObjectWriter::writeTableSection(ArrayRef<wasm::WasmTable> Tables) {
907 if (Tables.empty())
908 return;
909
910 SectionBookkeeping Section;
911 startSection(Section, wasm::WASM_SEC_TABLE);
912
913 encodeULEB128(Tables.size(), W->OS);
914 for (const wasm::WasmTable &Table : Tables) {
915 encodeULEB128(Table.Type.ElemType, W->OS);
916 encodeULEB128(Table.Type.Limits.Flags, W->OS);
917 encodeULEB128(Table.Type.Limits.Minimum, W->OS);
918 if (Table.Type.Limits.Flags & wasm::WASM_LIMITS_FLAG_HAS_MAX)
919 encodeULEB128(Table.Type.Limits.Maximum, W->OS);
920 }
921 endSection(Section);
922}
923
924void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
925 if (Exports.empty())
926 return;
927
928 SectionBookkeeping Section;
929 startSection(Section, wasm::WASM_SEC_EXPORT);
930
931 encodeULEB128(Exports.size(), W->OS);
932 for (const wasm::WasmExport &Export : Exports) {
933 writeString(Export.Name);
934 W->OS << char(Export.Kind);
935 encodeULEB128(Export.Index, W->OS);
936 }
937
938 endSection(Section);
939}
940
941void WasmObjectWriter::writeElemSection(
942 const MCSymbolWasm *IndirectFunctionTable, ArrayRef<uint32_t> TableElems) {
943 if (TableElems.empty())
944 return;
945
946 assert(IndirectFunctionTable)(static_cast<void> (0));
947
948 SectionBookkeeping Section;
949 startSection(Section, wasm::WASM_SEC_ELEM);
950
951 encodeULEB128(1, W->OS); // number of "segments"
952
953 assert(WasmIndices.count(IndirectFunctionTable))(static_cast<void> (0));
954 uint32_t TableNumber = WasmIndices.find(IndirectFunctionTable)->second;
955 uint32_t Flags = 0;
956 if (TableNumber)
957 Flags |= wasm::WASM_ELEM_SEGMENT_HAS_TABLE_NUMBER;
958 encodeULEB128(Flags, W->OS);
959 if (Flags & wasm::WASM_ELEM_SEGMENT_HAS_TABLE_NUMBER)
960 encodeULEB128(TableNumber, W->OS); // the table number
961
962 // init expr for starting offset
963 W->OS << char(wasm::WASM_OPCODE_I32_CONST);
964 encodeSLEB128(InitialTableOffset, W->OS);
965 W->OS << char(wasm::WASM_OPCODE_END);
966
967 if (Flags & wasm::WASM_ELEM_SEGMENT_MASK_HAS_ELEM_KIND) {
968 // We only write active function table initializers, for which the elem kind
969 // is specified to be written as 0x00 and interpreted to mean "funcref".
970 const uint8_t ElemKind = 0;
971 W->OS << ElemKind;
972 }
973
974 encodeULEB128(TableElems.size(), W->OS);
975 for (uint32_t Elem : TableElems)
976 encodeULEB128(Elem, W->OS);
977
978 endSection(Section);
979}
980
981void WasmObjectWriter::writeDataCountSection() {
982 if (DataSegments.empty())
983 return;
984
985 SectionBookkeeping Section;
986 startSection(Section, wasm::WASM_SEC_DATACOUNT);
987 encodeULEB128(DataSegments.size(), W->OS);
988 endSection(Section);
989}
990
991uint32_t WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
992 const MCAsmLayout &Layout,
993 ArrayRef<WasmFunction> Functions) {
994 if (Functions.empty())
995 return 0;
996
997 SectionBookkeeping Section;
998 startSection(Section, wasm::WASM_SEC_CODE);
999
1000 encodeULEB128(Functions.size(), W->OS);
1001
1002 for (const WasmFunction &Func : Functions) {
1003 auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
1004
1005 int64_t Size = 0;
1006 if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
1007 report_fatal_error(".size expression must be evaluatable");
1008
1009 encodeULEB128(Size, W->OS);
1010 FuncSection.setSectionOffset(W->OS.tell() - Section.ContentsOffset);
1011 Asm.writeSectionData(W->OS, &FuncSection, Layout);
1012 }
1013
1014 // Apply fixups.
1015 applyRelocations(CodeRelocations, Section.ContentsOffset, Layout);
1016
1017 endSection(Section);
1018 return Section.Index;
1019}
1020
1021uint32_t WasmObjectWriter::writeDataSection(const MCAsmLayout &Layout) {
1022 if (DataSegments.empty())
1023 return 0;
1024
1025 SectionBookkeeping Section;
1026 startSection(Section, wasm::WASM_SEC_DATA);
1027
1028 encodeULEB128(DataSegments.size(), W->OS); // count
1029
1030 for (const WasmDataSegment &Segment : DataSegments) {
1031 encodeULEB128(Segment.InitFlags, W->OS); // flags
1032 if (Segment.InitFlags & wasm::WASM_DATA_SEGMENT_HAS_MEMINDEX)
1033 encodeULEB128(0, W->OS); // memory index
1034 if ((Segment.InitFlags & wasm::WASM_DATA_SEGMENT_IS_PASSIVE) == 0) {
1035 W->OS << char(is64Bit() ? wasm::WASM_OPCODE_I64_CONST
1036 : wasm::WASM_OPCODE_I32_CONST);
1037 encodeSLEB128(Segment.Offset, W->OS); // offset
1038 W->OS << char(wasm::WASM_OPCODE_END);
1039 }
1040 encodeULEB128(Segment.Data.size(), W->OS); // size
1041 Segment.Section->setSectionOffset(W->OS.tell() - Section.ContentsOffset);
1042 W->OS << Segment.Data; // data
1043 }
1044
1045 // Apply fixups.
1046 applyRelocations(DataRelocations, Section.ContentsOffset, Layout);
1047
1048 endSection(Section);
1049 return Section.Index;
1050}
1051
1052void WasmObjectWriter::writeRelocSection(
1053 uint32_t SectionIndex, StringRef Name,
1054 std::vector<WasmRelocationEntry> &Relocs) {
1055 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
1056 // for descriptions of the reloc sections.
1057
1058 if (Relocs.empty())
1059 return;
1060
1061 // First, ensure the relocations are sorted in offset order. In general they
1062 // should already be sorted since `recordRelocation` is called in offset
1063 // order, but for the code section we combine many MC sections into single
1064 // wasm section, and this order is determined by the order of Asm.Symbols()
1065 // not the sections order.
1066 llvm::stable_sort(
1067 Relocs, [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
1068 return (A.Offset + A.FixupSection->getSectionOffset()) <
1069 (B.Offset + B.FixupSection->getSectionOffset());
1070 });
1071
1072 SectionBookkeeping Section;
1073 startCustomSection(Section, std::string("reloc.") + Name.str());
1074
1075 encodeULEB128(SectionIndex, W->OS);
1076 encodeULEB128(Relocs.size(), W->OS);
1077 for (const WasmRelocationEntry &RelEntry : Relocs) {
1078 uint64_t Offset =
1079 RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
1080 uint32_t Index = getRelocationIndexValue(RelEntry);
1081
1082 W->OS << char(RelEntry.Type);
1083 encodeULEB128(Offset, W->OS);
1084 encodeULEB128(Index, W->OS);
1085 if (RelEntry.hasAddend())
1086 encodeSLEB128(RelEntry.Addend, W->OS);
1087 }
1088
1089 endSection(Section);
1090}
1091
1092void WasmObjectWriter::writeCustomRelocSections() {
1093 for (const auto &Sec : CustomSections) {
1094 auto &Relocations = CustomSectionsRelocations[Sec.Section];
1095 writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
1096 }
1097}
1098
1099void WasmObjectWriter::writeLinkingMetaDataSection(
1100 ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
1101 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
1102 const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
1103 SectionBookkeeping Section;
1104 startCustomSection(Section, "linking");
1105 encodeULEB128(wasm::WasmMetadataVersion, W->OS);
1106
1107 SectionBookkeeping SubSection;
1108 if (SymbolInfos.size() != 0) {
1109 startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
1110 encodeULEB128(SymbolInfos.size(), W->OS);
1111 for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
1112 encodeULEB128(Sym.Kind, W->OS);
1113 encodeULEB128(Sym.Flags, W->OS);
1114 switch (Sym.Kind) {
1115 case wasm::WASM_SYMBOL_TYPE_FUNCTION:
1116 case wasm::WASM_SYMBOL_TYPE_GLOBAL:
1117 case wasm::WASM_SYMBOL_TYPE_TAG:
1118 case wasm::WASM_SYMBOL_TYPE_TABLE:
1119 encodeULEB128(Sym.ElementIndex, W->OS);
1120 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 ||
1121 (Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0)
1122 writeString(Sym.Name);
1123 break;
1124 case wasm::WASM_SYMBOL_TYPE_DATA:
1125 writeString(Sym.Name);
1126 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
1127 encodeULEB128(Sym.DataRef.Segment, W->OS);
1128 encodeULEB128(Sym.DataRef.Offset, W->OS);
1129 encodeULEB128(Sym.DataRef.Size, W->OS);
1130 }
1131 break;
1132 case wasm::WASM_SYMBOL_TYPE_SECTION: {
1133 const uint32_t SectionIndex =
1134 CustomSections[Sym.ElementIndex].OutputIndex;
1135 encodeULEB128(SectionIndex, W->OS);
1136 break;
1137 }
1138 default:
1139 llvm_unreachable("unexpected kind")__builtin_unreachable();
1140 }
1141 }
1142 endSection(SubSection);
1143 }
1144
1145 if (DataSegments.size()) {
1146 startSection(SubSection, wasm::WASM_SEGMENT_INFO);
1147 encodeULEB128(DataSegments.size(), W->OS);
1148 for (const WasmDataSegment &Segment : DataSegments) {
1149 writeString(Segment.Name);
1150 encodeULEB128(Segment.Alignment, W->OS);
1151 encodeULEB128(Segment.LinkingFlags, W->OS);
1152 }
1153 endSection(SubSection);
1154 }
1155
1156 if (!InitFuncs.empty()) {
1157 startSection(SubSection, wasm::WASM_INIT_FUNCS);
1158 encodeULEB128(InitFuncs.size(), W->OS);
1159 for (auto &StartFunc : InitFuncs) {
1160 encodeULEB128(StartFunc.first, W->OS); // priority
1161 encodeULEB128(StartFunc.second, W->OS); // function index
1162 }
1163 endSection(SubSection);
1164 }
1165
1166 if (Comdats.size()) {
1167 startSection(SubSection, wasm::WASM_COMDAT_INFO);
1168 encodeULEB128(Comdats.size(), W->OS);
1169 for (const auto &C : Comdats) {
1170 writeString(C.first);
1171 encodeULEB128(0, W->OS); // flags for future use
1172 encodeULEB128(C.second.size(), W->OS);
1173 for (const WasmComdatEntry &Entry : C.second) {
1174 encodeULEB128(Entry.Kind, W->OS);
1175 encodeULEB128(Entry.Index, W->OS);
1176 }
1177 }
1178 endSection(SubSection);
1179 }
1180
1181 endSection(Section);
1182}
1183
1184void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection,
1185 const MCAssembler &Asm,
1186 const MCAsmLayout &Layout) {
1187 SectionBookkeeping Section;
1188 auto *Sec = CustomSection.Section;
1189 startCustomSection(Section, CustomSection.Name);
1190
1191 Sec->setSectionOffset(W->OS.tell() - Section.ContentsOffset);
1192 Asm.writeSectionData(W->OS, Sec, Layout);
1193
1194 CustomSection.OutputContentsOffset = Section.ContentsOffset;
1195 CustomSection.OutputIndex = Section.Index;
1196
1197 endSection(Section);
1198
1199 // Apply fixups.
1200 auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
1201 applyRelocations(Relocations, CustomSection.OutputContentsOffset, Layout);
1202}
1203
1204uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
1205 assert(Symbol.isFunction())(static_cast<void> (0));
1206 assert(TypeIndices.count(&Symbol))(static_cast<void> (0));
1207 return TypeIndices[&Symbol];
1208}
1209
1210uint32_t WasmObjectWriter::getTagType(const MCSymbolWasm &Symbol) {
1211 assert(Symbol.isTag())(static_cast<void> (0));
1212 assert(TypeIndices.count(&Symbol))(static_cast<void> (0));
1213 return TypeIndices[&Symbol];
1214}
1215
1216void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
1217 assert(Symbol.isFunction())(static_cast<void> (0));
1218
1219 wasm::WasmSignature S;
1220
1221 if (auto *Sig = Symbol.getSignature()) {
1222 S.Returns = Sig->Returns;
1223 S.Params = Sig->Params;
1224 }
1225
1226 auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1227 if (Pair.second)
1228 Signatures.push_back(S);
1229 TypeIndices[&Symbol] = Pair.first->second;
1230
1231 LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symboldo { } while (false)
1232 << " new:" << Pair.second << "\n")do { } while (false);
1233 LLVM_DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n")do { } while (false);
1234}
1235
1236void WasmObjectWriter::registerTagType(const MCSymbolWasm &Symbol) {
1237 assert(Symbol.isTag())(static_cast<void> (0));
1238
1239 // TODO Currently we don't generate imported exceptions, but if we do, we
1240 // should have a way of infering types of imported exceptions.
1241 wasm::WasmSignature S;
1242 if (auto *Sig = Symbol.getSignature()) {
1243 S.Returns = Sig->Returns;
1244 S.Params = Sig->Params;
1245 }
1246
1247 auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1248 if (Pair.second)
1249 Signatures.push_back(S);
1250 TypeIndices[&Symbol] = Pair.first->second;
1251
1252 LLVM_DEBUG(dbgs() << "registerTagType: " << Symbol << " new:" << Pair.seconddo { } while (false)
1253 << "\n")do { } while (false);
1254 LLVM_DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n")do { } while (false);
1255}
1256
1257static bool isInSymtab(const MCSymbolWasm &Sym) {
1258 if (Sym.isUsedInReloc() || Sym.isUsedInInitArray())
1259 return true;
1260
1261 if (Sym.isComdat() && !Sym.isDefined())
1262 return false;
1263
1264 if (Sym.isTemporary())
1265 return false;
1266
1267 if (Sym.isSection())
1268 return false;
1269
1270 if (Sym.omitFromLinkingSection())
1271 return false;
1272
1273 return true;
1274}
1275
1276void WasmObjectWriter::prepareImports(
1277 SmallVectorImpl<wasm::WasmImport> &Imports, MCAssembler &Asm,
1278 const MCAsmLayout &Layout) {
1279 // For now, always emit the memory import, since loads and stores are not
1280 // valid without it. In the future, we could perhaps be more clever and omit
1281 // it if there are no loads or stores.
1282 wasm::WasmImport MemImport;
1283 MemImport.Module = "env";
1284 MemImport.Field = "__linear_memory";
1285 MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1286 MemImport.Memory.Flags = is64Bit() ? wasm::WASM_LIMITS_FLAG_IS_64
1287 : wasm::WASM_LIMITS_FLAG_NONE;
1288 Imports.push_back(MemImport);
1289
1290 // Populate SignatureIndices, and Imports and WasmIndices for undefined
1291 // symbols. This must be done before populating WasmIndices for defined
1292 // symbols.
1293 for (const MCSymbol &S : Asm.symbols()) {
1294 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1295
1296 // Register types for all functions, including those with private linkage
1297 // (because wasm always needs a type signature).
1298 if (WS.isFunction()) {
1299 const auto *BS = Layout.getBaseSymbol(S);
1300 if (!BS)
1301 report_fatal_error(Twine(S.getName()) +
1302 ": absolute addressing not supported!");
1303 registerFunctionType(*cast<MCSymbolWasm>(BS));
1304 }
1305
1306 if (WS.isTag())
1307 registerTagType(WS);
1308
1309 if (WS.isTemporary())
1310 continue;
1311
1312 // If the symbol is not defined in this translation unit, import it.
1313 if (!WS.isDefined() && !WS.isComdat()) {
1314 if (WS.isFunction()) {
1315 wasm::WasmImport Import;
1316 Import.Module = WS.getImportModule();
1317 Import.Field = WS.getImportName();
1318 Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1319 Import.SigIndex = getFunctionType(WS);
1320 Imports.push_back(Import);
1321 assert(WasmIndices.count(&WS) == 0)(static_cast<void> (0));
1322 WasmIndices[&WS] = NumFunctionImports++;
1323 } else if (WS.isGlobal()) {
1324 if (WS.isWeak())
1325 report_fatal_error("undefined global symbol cannot be weak");
1326
1327 wasm::WasmImport Import;
1328 Import.Field = WS.getImportName();
1329 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1330 Import.Module = WS.getImportModule();
1331 Import.Global = WS.getGlobalType();
1332 Imports.push_back(Import);
1333 assert(WasmIndices.count(&WS) == 0)(static_cast<void> (0));
1334 WasmIndices[&WS] = NumGlobalImports++;
1335 } else if (WS.isTag()) {
1336 if (WS.isWeak())
1337 report_fatal_error("undefined tag symbol cannot be weak");
1338
1339 wasm::WasmImport Import;
1340 Import.Module = WS.getImportModule();
1341 Import.Field = WS.getImportName();
1342 Import.Kind = wasm::WASM_EXTERNAL_TAG;
1343 Import.Tag.Attribute = wasm::WASM_TAG_ATTRIBUTE_EXCEPTION;
1344 Import.Tag.SigIndex = getTagType(WS);
1345 Imports.push_back(Import);
1346 assert(WasmIndices.count(&WS) == 0)(static_cast<void> (0));
1347 WasmIndices[&WS] = NumTagImports++;
1348 } else if (WS.isTable()) {
1349 if (WS.isWeak())
1350 report_fatal_error("undefined table symbol cannot be weak");
1351
1352 wasm::WasmImport Import;
1353 Import.Module = WS.getImportModule();
1354 Import.Field = WS.getImportName();
1355 Import.Kind = wasm::WASM_EXTERNAL_TABLE;
1356 Import.Table = WS.getTableType();
1357 Imports.push_back(Import);
1358 assert(WasmIndices.count(&WS) == 0)(static_cast<void> (0));
1359 WasmIndices[&WS] = NumTableImports++;
1360 }
1361 }
1362 }
1363
1364 // Add imports for GOT globals
1365 for (const MCSymbol &S : Asm.symbols()) {
1366 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1367 if (WS.isUsedInGOT()) {
1368 wasm::WasmImport Import;
1369 if (WS.isFunction())
1370 Import.Module = "GOT.func";
1371 else
1372 Import.Module = "GOT.mem";
1373 Import.Field = WS.getName();
1374 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1375 Import.Global = {wasm::WASM_TYPE_I32, true};
1376 Imports.push_back(Import);
1377 assert(GOTIndices.count(&WS) == 0)(static_cast<void> (0));
1378 GOTIndices[&WS] = NumGlobalImports++;
1379 }
1380 }
1381}
1382
1383uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
1384 const MCAsmLayout &Layout) {
1385 support::endian::Writer MainWriter(*OS, support::little);
1386 W = &MainWriter;
1387 if (IsSplitDwarf) {
1388 uint64_t TotalSize = writeOneObject(Asm, Layout, DwoMode::NonDwoOnly);
1389 assert(DwoOS)(static_cast<void> (0));
1390 support::endian::Writer DwoWriter(*DwoOS, support::little);
1391 W = &DwoWriter;
1392 return TotalSize + writeOneObject(Asm, Layout, DwoMode::DwoOnly);
1393 } else {
1394 return writeOneObject(Asm, Layout, DwoMode::AllSections);
1395 }
1396}
1397
1398uint64_t WasmObjectWriter::writeOneObject(MCAssembler &Asm,
1399 const MCAsmLayout &Layout,
1400 DwoMode Mode) {
1401 uint64_t StartOffset = W->OS.tell();
1402 SectionCount = 0;
1403 CustomSections.clear();
1404
1405 LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n")do { } while (false);
1406
1407 // Collect information from the available symbols.
1408 SmallVector<WasmFunction, 4> Functions;
1409 SmallVector<uint32_t, 4> TableElems;
1410 SmallVector<wasm::WasmImport, 4> Imports;
1411 SmallVector<wasm::WasmExport, 4> Exports;
1412 SmallVector<wasm::WasmTagType, 1> Tags;
1413 SmallVector<wasm::WasmGlobal, 1> Globals;
1414 SmallVector<wasm::WasmTable, 1> Tables;
1415 SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
1416 SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
1417 std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
1418 uint64_t DataSize = 0;
1419 if (Mode != DwoMode::DwoOnly) {
1420 prepareImports(Imports, Asm, Layout);
1421 }
1422
1423 // Populate DataSegments and CustomSections, which must be done before
1424 // populating DataLocations.
1425 for (MCSection &Sec : Asm) {
1426 auto &Section = static_cast<MCSectionWasm &>(Sec);
1427 StringRef SectionName = Section.getName();
1428
1429 if (Mode == DwoMode::NonDwoOnly && isDwoSection(Sec))
1430 continue;
1431 if (Mode == DwoMode::DwoOnly && !isDwoSection(Sec))
1432 continue;
1433
1434 LLVM_DEBUG(dbgs() << "Processing Section " << SectionName << " group "do { } while (false)
1435 << Section.getGroup() << "\n";)do { } while (false);
1436
1437 // .init_array sections are handled specially elsewhere.
1438 if (SectionName.startswith(".init_array"))
1439 continue;
1440
1441 // Code is handled separately
1442 if (Section.getKind().isText())
1443 continue;
1444
1445 if (Section.isWasmData()) {
1446 uint32_t SegmentIndex = DataSegments.size();
1447 DataSize = alignTo(DataSize, Section.getAlignment());
1448 DataSegments.emplace_back();
1449 WasmDataSegment &Segment = DataSegments.back();
1450 Segment.Name = SectionName;
1451 Segment.InitFlags = Section.getPassive()
1452 ? (uint32_t)wasm::WASM_DATA_SEGMENT_IS_PASSIVE
1453 : 0;
1454 Segment.Offset = DataSize;
1455 Segment.Section = &Section;
1456 addData(Segment.Data, Section);
1457 Segment.Alignment = Log2_32(Section.getAlignment());
1458 Segment.LinkingFlags = Section.getSegmentFlags();
1459 DataSize += Segment.Data.size();
1460 Section.setSegmentIndex(SegmentIndex);
1461
1462 if (const MCSymbolWasm *C = Section.getGroup()) {
1463 Comdats[C->getName()].emplace_back(
1464 WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1465 }
1466 } else {
1467 // Create custom sections
1468 assert(Sec.getKind().isMetadata())(static_cast<void> (0));
1469
1470 StringRef Name = SectionName;
1471
1472 // For user-defined custom sections, strip the prefix
1473 if (Name.startswith(".custom_section."))
1474 Name = Name.substr(strlen(".custom_section."));
1475
1476 MCSymbol *Begin = Sec.getBeginSymbol();
1477 if (Begin) {
1478 assert(WasmIndices.count(cast<MCSymbolWasm>(Begin)) == 0)(static_cast<void> (0));
1479 WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
1480 }
1481
1482 // Separate out the producers and target features sections
1483 if (Name == "producers") {
1484 ProducersSection = std::make_unique<WasmCustomSection>(Name, &Section);
1485 continue;
1486 }
1487 if (Name == "target_features") {
1488 TargetFeaturesSection =
1489 std::make_unique<WasmCustomSection>(Name, &Section);
1490 continue;
1491 }
1492
1493 // Custom sections can also belong to COMDAT groups. In this case the
1494 // decriptor's "index" field is the section index (in the final object
1495 // file), but that is not known until after layout, so it must be fixed up
1496 // later
1497 if (const MCSymbolWasm *C = Section.getGroup()) {
1498 Comdats[C->getName()].emplace_back(
1499 WasmComdatEntry{wasm::WASM_COMDAT_SECTION,
1500 static_cast<uint32_t>(CustomSections.size())});
1501 }
1502
1503 CustomSections.emplace_back(Name, &Section);
1504 }
1505 }
1506
1507 if (Mode != DwoMode::DwoOnly) {
1508 // Populate WasmIndices and DataLocations for defined symbols.
1509 for (const MCSymbol &S : Asm.symbols()) {
1510 // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1511 // or used in relocations.
1512 if (S.isTemporary() && S.getName().empty())
1513 continue;
1514
1515 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1516 LLVM_DEBUG(dbgs()do { } while (false)
1517 << "MCSymbol: "do { } while (false)
1518 << toString(WS.getType().getValueOr(wasm::WASM_SYMBOL_TYPE_DATA))do { } while (false)
1519 << " '" << S << "'"do { } while (false)
1520 << " isDefined=" << S.isDefined() << " isExternal="do { } while (false)
1521 << S.isExternal() << " isTemporary=" << S.isTemporary()do { } while (false)
1522 << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()do { } while (false)
1523 << " isVariable=" << WS.isVariable() << "\n")do { } while (false);
1524
1525 if (WS.isVariable())
1526 continue;
1527 if (WS.isComdat() && !WS.isDefined())
1528 continue;
1529
1530 if (WS.isFunction()) {
1531 unsigned Index;
1532 if (WS.isDefined()) {
1533 if (WS.getOffset() != 0)
1534 report_fatal_error(
1535 "function sections must contain one function each");
1536
1537 if (WS.getSize() == nullptr)
1538 report_fatal_error(
1539 "function symbols must have a size set with .size");
1540
1541 // A definition. Write out the function body.
1542 Index = NumFunctionImports + Functions.size();
1543 WasmFunction Func;
1544 Func.SigIndex = getFunctionType(WS);
1545 Func.Sym = &WS;
1546 assert(WasmIndices.count(&WS) == 0)(static_cast<void> (0));
1547 WasmIndices[&WS] = Index;
1548 Functions.push_back(Func);
1549
1550 auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
1551 if (const MCSymbolWasm *C = Section.getGroup()) {
1552 Comdats[C->getName()].emplace_back(
1553 WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
1554 }
1555
1556 if (WS.hasExportName()) {
1557 wasm::WasmExport Export;
1558 Export.Name = WS.getExportName();
1559 Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1560 Export.Index = Index;
1561 Exports.push_back(Export);
1562 }
1563 } else {
1564 // An import; the index was assigned above.
1565 Index = WasmIndices.find(&WS)->second;
Value stored to 'Index' is never read
1566 }
1567
1568 LLVM_DEBUG(dbgs() << " -> function index: " << Index << "\n")do { } while (false);
1569
1570 } else if (WS.isData()) {
1571 if (!isInSymtab(WS))
1572 continue;
1573
1574 if (!WS.isDefined()) {
1575 LLVM_DEBUG(dbgs() << " -> segment index: -1"do { } while (false)
1576 << "\n")do { } while (false);
1577 continue;
1578 }
1579
1580 if (!WS.getSize())
1581 report_fatal_error("data symbols must have a size set with .size: " +
1582 WS.getName());
1583
1584 int64_t Size = 0;
1585 if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1586 report_fatal_error(".size expression must be evaluatable");
1587
1588 auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1589 if (!DataSection.isWasmData())
1590 report_fatal_error("data symbols must live in a data section: " +
1591 WS.getName());
1592
1593 // For each data symbol, export it in the symtab as a reference to the
1594 // corresponding Wasm data segment.
1595 wasm::WasmDataReference Ref = wasm::WasmDataReference{
1596 DataSection.getSegmentIndex(), Layout.getSymbolOffset(WS),
1597 static_cast<uint64_t>(Size)};
1598 assert(DataLocations.count(&WS) == 0)(static_cast<void> (0));
1599 DataLocations[&WS] = Ref;
1600 LLVM_DEBUG(dbgs() << " -> segment index: " << Ref.Segment << "\n")do { } while (false);
1601
1602 } else if (WS.isGlobal()) {
1603 // A "true" Wasm global (currently just __stack_pointer)
1604 if (WS.isDefined()) {
1605 wasm::WasmGlobal Global;
1606 Global.Type = WS.getGlobalType();
1607 Global.Index = NumGlobalImports + Globals.size();
1608 switch (Global.Type.Type) {
1609 case wasm::WASM_TYPE_I32:
1610 Global.InitExpr.Opcode = wasm::WASM_OPCODE_I32_CONST;
1611 break;
1612 case wasm::WASM_TYPE_I64:
1613 Global.InitExpr.Opcode = wasm::WASM_OPCODE_I64_CONST;
1614 break;
1615 case wasm::WASM_TYPE_F32:
1616 Global.InitExpr.Opcode = wasm::WASM_OPCODE_F32_CONST;
1617 break;
1618 case wasm::WASM_TYPE_F64:
1619 Global.InitExpr.Opcode = wasm::WASM_OPCODE_F64_CONST;
1620 break;
1621 case wasm::WASM_TYPE_EXTERNREF:
1622 Global.InitExpr.Opcode = wasm::WASM_OPCODE_REF_NULL;
1623 break;
1624 default:
1625 llvm_unreachable("unexpected type")__builtin_unreachable();
1626 }
1627 assert(WasmIndices.count(&WS) == 0)(static_cast<void> (0));
1628 WasmIndices[&WS] = Global.Index;
1629 Globals.push_back(Global);
1630 } else {
1631 // An import; the index was assigned above
1632 LLVM_DEBUG(dbgs() << " -> global index: "do { } while (false)
1633 << WasmIndices.find(&WS)->second << "\n")do { } while (false);
1634 }
1635 } else if (WS.isTable()) {
1636 if (WS.isDefined()) {
1637 wasm::WasmTable Table;
1638 Table.Index = NumTableImports + Tables.size();
1639 Table.Type = WS.getTableType();
1640 assert(WasmIndices.count(&WS) == 0)(static_cast<void> (0));
1641 WasmIndices[&WS] = Table.Index;
1642 Tables.push_back(Table);
1643 }
1644 LLVM_DEBUG(dbgs() << " -> table index: "do { } while (false)
1645 << WasmIndices.find(&WS)->second << "\n")do { } while (false);
1646 } else if (WS.isTag()) {
1647 // C++ exception symbol (__cpp_exception) or longjmp symbol
1648 // (__c_longjmp)
1649 unsigned Index;
1650 if (WS.isDefined()) {
1651 Index = NumTagImports + Tags.size();
1652 wasm::WasmTagType Tag;
1653 Tag.SigIndex = getTagType(WS);
1654 Tag.Attribute = wasm::WASM_TAG_ATTRIBUTE_EXCEPTION;
1655 assert(WasmIndices.count(&WS) == 0)(static_cast<void> (0));
1656 WasmIndices[&WS] = Index;
1657 Tags.push_back(Tag);
1658 } else {
1659 // An import; the index was assigned above.
1660 assert(WasmIndices.count(&WS) > 0)(static_cast<void> (0));
1661 }
1662 LLVM_DEBUG(dbgs() << " -> tag index: " << WasmIndices.find(&WS)->seconddo { } while (false)
1663 << "\n")do { } while (false);
1664
1665 } else {
1666 assert(WS.isSection())(static_cast<void> (0));
1667 }
1668 }
1669
1670 // Populate WasmIndices and DataLocations for aliased symbols. We need to
1671 // process these in a separate pass because we need to have processed the
1672 // target of the alias before the alias itself and the symbols are not
1673 // necessarily ordered in this way.
1674 for (const MCSymbol &S : Asm.symbols()) {
1675 if (!S.isVariable())
1676 continue;
1677
1678 assert(S.isDefined())(static_cast<void> (0));
1679
1680 const auto *BS = Layout.getBaseSymbol(S);
1681 if (!BS)
1682 report_fatal_error(Twine(S.getName()) +
1683 ": absolute addressing not supported!");
1684 const MCSymbolWasm *Base = cast<MCSymbolWasm>(BS);
1685
1686 // Find the target symbol of this weak alias and export that index
1687 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1688 LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *Basedo { } while (false)
1689 << "'\n")do { } while (false);
1690
1691 if (Base->isFunction()) {
1692 assert(WasmIndices.count(Base) > 0)(static_cast<void> (0));
1693 uint32_t WasmIndex = WasmIndices.find(Base)->second;
1694 assert(WasmIndices.count(&WS) == 0)(static_cast<void> (0));
1695 WasmIndices[&WS] = WasmIndex;
1696 LLVM_DEBUG(dbgs() << " -> index:" << WasmIndex << "\n")do { } while (false);
1697 } else if (Base->isData()) {
1698 auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1699 uint64_t Offset = Layout.getSymbolOffset(S);
1700 int64_t Size = 0;
1701 // For data symbol alias we use the size of the base symbol as the
1702 // size of the alias. When an offset from the base is involved this
1703 // can result in a offset + size goes past the end of the data section
1704 // which out object format doesn't support. So we must clamp it.
1705 if (!Base->getSize()->evaluateAsAbsolute(Size, Layout))
1706 report_fatal_error(".size expression must be evaluatable");
1707 const WasmDataSegment &Segment =
1708 DataSegments[DataSection.getSegmentIndex()];
1709 Size =
1710 std::min(static_cast<uint64_t>(Size), Segment.Data.size() - Offset);
1711 wasm::WasmDataReference Ref = wasm::WasmDataReference{
1712 DataSection.getSegmentIndex(),
1713 static_cast<uint32_t>(Layout.getSymbolOffset(S)),
1714 static_cast<uint32_t>(Size)};
1715 DataLocations[&WS] = Ref;
1716 LLVM_DEBUG(dbgs() << " -> index:" << Ref.Segment << "\n")do { } while (false);
1717 } else {
1718 report_fatal_error("don't yet support global/tag aliases");
1719 }
1720 }
1721 }
1722
1723 // Finally, populate the symbol table itself, in its "natural" order.
1724 for (const MCSymbol &S : Asm.symbols()) {
1725 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1726 if (!isInSymtab(WS)) {
1727 WS.setIndex(InvalidIndex);
1728 continue;
1729 }
1730 LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n")do { } while (false);
1731
1732 uint32_t Flags = 0;
1733 if (WS.isWeak())
1734 Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1735 if (WS.isHidden())
1736 Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1737 if (!WS.isExternal() && WS.isDefined())
1738 Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1739 if (WS.isUndefined())
1740 Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1741 if (WS.isNoStrip()) {
1742 Flags |= wasm::WASM_SYMBOL_NO_STRIP;
1743 if (isEmscripten()) {
1744 Flags |= wasm::WASM_SYMBOL_EXPORTED;
1745 }
1746 }
1747 if (WS.hasImportName())
1748 Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME;
1749 if (WS.hasExportName())
1750 Flags |= wasm::WASM_SYMBOL_EXPORTED;
1751
1752 wasm::WasmSymbolInfo Info;
1753 Info.Name = WS.getName();
1754 Info.Kind = WS.getType().getValueOr(wasm::WASM_SYMBOL_TYPE_DATA);
1755 Info.Flags = Flags;
1756 if (!WS.isData()) {
1757 assert(WasmIndices.count(&WS) > 0)(static_cast<void> (0));
1758 Info.ElementIndex = WasmIndices.find(&WS)->second;
1759 } else if (WS.isDefined()) {
1760 assert(DataLocations.count(&WS) > 0)(static_cast<void> (0));
1761 Info.DataRef = DataLocations.find(&WS)->second;
1762 }
1763 WS.setIndex(SymbolInfos.size());
1764 SymbolInfos.emplace_back(Info);
1765 }
1766
1767 {
1768 auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
1769 // Functions referenced by a relocation need to put in the table. This is
1770 // purely to make the object file's provisional values readable, and is
1771 // ignored by the linker, which re-calculates the relocations itself.
1772 if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 &&
1773 Rel.Type != wasm::R_WASM_TABLE_INDEX_I64 &&
1774 Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB &&
1775 Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB64 &&
1776 Rel.Type != wasm::R_WASM_TABLE_INDEX_REL_SLEB &&
1777 Rel.Type != wasm::R_WASM_TABLE_INDEX_REL_SLEB64)
1778 return;
1779 assert(Rel.Symbol->isFunction())(static_cast<void> (0));
1780 const MCSymbolWasm *Base =
1781 cast<MCSymbolWasm>(Layout.getBaseSymbol(*Rel.Symbol));
1782 uint32_t FunctionIndex = WasmIndices.find(Base)->second;
1783 uint32_t TableIndex = TableElems.size() + InitialTableOffset;
1784 if (TableIndices.try_emplace(Base, TableIndex).second) {
1785 LLVM_DEBUG(dbgs() << " -> adding " << Base->getName()do { } while (false)
1786 << " to table: " << TableIndex << "\n")do { } while (false);
1787 TableElems.push_back(FunctionIndex);
1788 registerFunctionType(*Base);
1789 }
1790 };
1791
1792 for (const WasmRelocationEntry &RelEntry : CodeRelocations)
1793 HandleReloc(RelEntry);
1794 for (const WasmRelocationEntry &RelEntry : DataRelocations)
1795 HandleReloc(RelEntry);
1796 }
1797
1798 // Translate .init_array section contents into start functions.
1799 for (const MCSection &S : Asm) {
1800 const auto &WS = static_cast<const MCSectionWasm &>(S);
1801 if (WS.getName().startswith(".fini_array"))
1802 report_fatal_error(".fini_array sections are unsupported");
1803 if (!WS.getName().startswith(".init_array"))
1804 continue;
1805 if (WS.getFragmentList().empty())
1806 continue;
1807
1808 // init_array is expected to contain a single non-empty data fragment
1809 if (WS.getFragmentList().size() != 3)
1810 report_fatal_error("only one .init_array section fragment supported");
1811
1812 auto IT = WS.begin();
1813 const MCFragment &EmptyFrag = *IT;
1814 if (EmptyFrag.getKind() != MCFragment::FT_Data)
1815 report_fatal_error(".init_array section should be aligned");
1816
1817 IT = std::next(IT);
1818 const MCFragment &AlignFrag = *IT;
1819 if (AlignFrag.getKind() != MCFragment::FT_Align)
1820 report_fatal_error(".init_array section should be aligned");
1821 if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1822 report_fatal_error(".init_array section should be aligned for pointers");
1823
1824 const MCFragment &Frag = *std::next(IT);
1825 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1826 report_fatal_error("only data supported in .init_array section");
1827
1828 uint16_t Priority = UINT16_MAX(65535);
1829 unsigned PrefixLength = strlen(".init_array");
1830 if (WS.getName().size() > PrefixLength) {
1831 if (WS.getName()[PrefixLength] != '.')
1832 report_fatal_error(
1833 ".init_array section priority should start with '.'");
1834 if (WS.getName().substr(PrefixLength + 1).getAsInteger(10, Priority))
1835 report_fatal_error("invalid .init_array section priority");
1836 }
1837 const auto &DataFrag = cast<MCDataFragment>(Frag);
1838 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1839 for (const uint8_t *
1840 P = (const uint8_t *)Contents.data(),
1841 *End = (const uint8_t *)Contents.data() + Contents.size();
1842 P != End; ++P) {
1843 if (*P != 0)
1844 report_fatal_error("non-symbolic data in .init_array section");
1845 }
1846 for (const MCFixup &Fixup : DataFrag.getFixups()) {
1847 assert(Fixup.getKind() ==(static_cast<void> (0))
1848 MCFixup::getKindForSize(is64Bit() ? 8 : 4, false))(static_cast<void> (0));
1849 const MCExpr *Expr = Fixup.getValue();
1850 auto *SymRef = dyn_cast<MCSymbolRefExpr>(Expr);
1851 if (!SymRef)
1852 report_fatal_error("fixups in .init_array should be symbol references");
1853 const auto &TargetSym = cast<const MCSymbolWasm>(SymRef->getSymbol());
1854 if (TargetSym.getIndex() == InvalidIndex)
1855 report_fatal_error("symbols in .init_array should exist in symtab");
1856 if (!TargetSym.isFunction())
1857 report_fatal_error("symbols in .init_array should be for functions");
1858 InitFuncs.push_back(
1859 std::make_pair(Priority, TargetSym.getIndex()));
1860 }
1861 }
1862
1863 // Write out the Wasm header.
1864 writeHeader(Asm);
1865
1866 uint32_t CodeSectionIndex, DataSectionIndex;
1867 if (Mode != DwoMode::DwoOnly) {
1868 writeTypeSection(Signatures);
1869 writeImportSection(Imports, DataSize, TableElems.size());
1870 writeFunctionSection(Functions);
1871 writeTableSection(Tables);
1872 // Skip the "memory" section; we import the memory instead.
1873 writeTagSection(Tags);
1874 writeGlobalSection(Globals);
1875 writeExportSection(Exports);
1876 const MCSymbol *IndirectFunctionTable =
1877 Asm.getContext().lookupSymbol("__indirect_function_table");
1878 writeElemSection(cast_or_null<const MCSymbolWasm>(IndirectFunctionTable),
1879 TableElems);
1880 writeDataCountSection();
1881
1882 CodeSectionIndex = writeCodeSection(Asm, Layout, Functions);
1883 DataSectionIndex = writeDataSection(Layout);
1884 }
1885
1886 // The Sections in the COMDAT list have placeholder indices (their index among
1887 // custom sections, rather than among all sections). Fix them up here.
1888 for (auto &Group : Comdats) {
1889 for (auto &Entry : Group.second) {
1890 if (Entry.Kind == wasm::WASM_COMDAT_SECTION) {
1891 Entry.Index += SectionCount;
1892 }
1893 }
1894 }
1895 for (auto &CustomSection : CustomSections)
1896 writeCustomSection(CustomSection, Asm, Layout);
1897
1898 if (Mode != DwoMode::DwoOnly) {
1899 writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
1900
1901 writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
1902 writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
1903 }
1904 writeCustomRelocSections();
1905 if (ProducersSection)
1906 writeCustomSection(*ProducersSection, Asm, Layout);
1907 if (TargetFeaturesSection)
1908 writeCustomSection(*TargetFeaturesSection, Asm, Layout);
1909
1910 // TODO: Translate the .comment section to the output.
1911 return W->OS.tell() - StartOffset;
1912}
1913
1914std::unique_ptr<MCObjectWriter>
1915llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1916 raw_pwrite_stream &OS) {
1917 return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
1918}
1919
1920std::unique_ptr<MCObjectWriter>
1921llvm::createWasmDwoObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1922 raw_pwrite_stream &OS,
1923 raw_pwrite_stream &DwoOS) {
1924 return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS, DwoOS);
1925}