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