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