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