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 default: 837 llvm_unreachable("unexpected type"); 838 } 839 W.OS << char(wasm::WASM_OPCODE_END); 840 } 841 842 endSection(Section); 843 } 844 845 void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) { 846 if (Exports.empty()) 847 return; 848 849 SectionBookkeeping Section; 850 startSection(Section, wasm::WASM_SEC_EXPORT); 851 852 encodeULEB128(Exports.size(), W.OS); 853 for (const wasm::WasmExport &Export : Exports) { 854 writeString(Export.Name); 855 W.OS << char(Export.Kind); 856 encodeULEB128(Export.Index, W.OS); 857 } 858 859 endSection(Section); 860 } 861 862 void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) { 863 if (TableElems.empty()) 864 return; 865 866 SectionBookkeeping Section; 867 startSection(Section, wasm::WASM_SEC_ELEM); 868 869 encodeULEB128(1, W.OS); // number of "segments" 870 encodeULEB128(0, W.OS); // the table index 871 872 // init expr for starting offset 873 W.OS << char(wasm::WASM_OPCODE_I32_CONST); 874 encodeSLEB128(InitialTableOffset, W.OS); 875 W.OS << char(wasm::WASM_OPCODE_END); 876 877 encodeULEB128(TableElems.size(), W.OS); 878 for (uint32_t Elem : TableElems) 879 encodeULEB128(Elem, W.OS); 880 881 endSection(Section); 882 } 883 884 void WasmObjectWriter::writeDataCountSection() { 885 if (DataSegments.empty()) 886 return; 887 888 SectionBookkeeping Section; 889 startSection(Section, wasm::WASM_SEC_DATACOUNT); 890 encodeULEB128(DataSegments.size(), W.OS); 891 endSection(Section); 892 } 893 894 void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm, 895 const MCAsmLayout &Layout, 896 ArrayRef<WasmFunction> Functions) { 897 if (Functions.empty()) 898 return; 899 900 SectionBookkeeping Section; 901 startSection(Section, wasm::WASM_SEC_CODE); 902 CodeSectionIndex = Section.Index; 903 904 encodeULEB128(Functions.size(), W.OS); 905 906 for (const WasmFunction &Func : Functions) { 907 auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection()); 908 909 int64_t Size = 0; 910 if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout)) 911 report_fatal_error(".size expression must be evaluatable"); 912 913 encodeULEB128(Size, W.OS); 914 FuncSection.setSectionOffset(W.OS.tell() - Section.ContentsOffset); 915 Asm.writeSectionData(W.OS, &FuncSection, Layout); 916 } 917 918 // Apply fixups. 919 applyRelocations(CodeRelocations, Section.ContentsOffset, Layout); 920 921 endSection(Section); 922 } 923 924 void WasmObjectWriter::writeDataSection(const MCAsmLayout &Layout) { 925 if (DataSegments.empty()) 926 return; 927 928 SectionBookkeeping Section; 929 startSection(Section, wasm::WASM_SEC_DATA); 930 DataSectionIndex = Section.Index; 931 932 encodeULEB128(DataSegments.size(), W.OS); // count 933 934 for (const WasmDataSegment &Segment : DataSegments) { 935 encodeULEB128(Segment.InitFlags, W.OS); // flags 936 if (Segment.InitFlags & wasm::WASM_SEGMENT_HAS_MEMINDEX) 937 encodeULEB128(0, W.OS); // memory index 938 if ((Segment.InitFlags & wasm::WASM_SEGMENT_IS_PASSIVE) == 0) { 939 W.OS << char(wasm::WASM_OPCODE_I32_CONST); 940 encodeSLEB128(Segment.Offset, W.OS); // offset 941 W.OS << char(wasm::WASM_OPCODE_END); 942 } 943 encodeULEB128(Segment.Data.size(), W.OS); // size 944 Segment.Section->setSectionOffset(W.OS.tell() - Section.ContentsOffset); 945 W.OS << Segment.Data; // data 946 } 947 948 // Apply fixups. 949 applyRelocations(DataRelocations, Section.ContentsOffset, Layout); 950 951 endSection(Section); 952 } 953 954 void WasmObjectWriter::writeRelocSection( 955 uint32_t SectionIndex, StringRef Name, 956 std::vector<WasmRelocationEntry> &Relocs) { 957 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md 958 // for descriptions of the reloc sections. 959 960 if (Relocs.empty()) 961 return; 962 963 // First, ensure the relocations are sorted in offset order. In general they 964 // should already be sorted since `recordRelocation` is called in offset 965 // order, but for the code section we combine many MC sections into single 966 // wasm section, and this order is determined by the order of Asm.Symbols() 967 // not the sections order. 968 llvm::stable_sort( 969 Relocs, [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) { 970 return (A.Offset + A.FixupSection->getSectionOffset()) < 971 (B.Offset + B.FixupSection->getSectionOffset()); 972 }); 973 974 SectionBookkeeping Section; 975 startCustomSection(Section, std::string("reloc.") + Name.str()); 976 977 encodeULEB128(SectionIndex, W.OS); 978 encodeULEB128(Relocs.size(), W.OS); 979 for (const WasmRelocationEntry &RelEntry : Relocs) { 980 uint64_t Offset = 981 RelEntry.Offset + RelEntry.FixupSection->getSectionOffset(); 982 uint32_t Index = getRelocationIndexValue(RelEntry); 983 984 W.OS << char(RelEntry.Type); 985 encodeULEB128(Offset, W.OS); 986 encodeULEB128(Index, W.OS); 987 if (RelEntry.hasAddend()) 988 encodeSLEB128(RelEntry.Addend, W.OS); 989 } 990 991 endSection(Section); 992 } 993 994 void WasmObjectWriter::writeCustomRelocSections() { 995 for (const auto &Sec : CustomSections) { 996 auto &Relocations = CustomSectionsRelocations[Sec.Section]; 997 writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations); 998 } 999 } 1000 1001 void WasmObjectWriter::writeLinkingMetaDataSection( 1002 ArrayRef<wasm::WasmSymbolInfo> SymbolInfos, 1003 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs, 1004 const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) { 1005 SectionBookkeeping Section; 1006 startCustomSection(Section, "linking"); 1007 encodeULEB128(wasm::WasmMetadataVersion, W.OS); 1008 1009 SectionBookkeeping SubSection; 1010 if (SymbolInfos.size() != 0) { 1011 startSection(SubSection, wasm::WASM_SYMBOL_TABLE); 1012 encodeULEB128(SymbolInfos.size(), W.OS); 1013 for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) { 1014 encodeULEB128(Sym.Kind, W.OS); 1015 encodeULEB128(Sym.Flags, W.OS); 1016 switch (Sym.Kind) { 1017 case wasm::WASM_SYMBOL_TYPE_FUNCTION: 1018 case wasm::WASM_SYMBOL_TYPE_GLOBAL: 1019 case wasm::WASM_SYMBOL_TYPE_EVENT: 1020 encodeULEB128(Sym.ElementIndex, W.OS); 1021 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 || 1022 (Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) 1023 writeString(Sym.Name); 1024 break; 1025 case wasm::WASM_SYMBOL_TYPE_DATA: 1026 writeString(Sym.Name); 1027 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) { 1028 encodeULEB128(Sym.DataRef.Segment, W.OS); 1029 encodeULEB128(Sym.DataRef.Offset, W.OS); 1030 encodeULEB128(Sym.DataRef.Size, W.OS); 1031 } 1032 break; 1033 case wasm::WASM_SYMBOL_TYPE_SECTION: { 1034 const uint32_t SectionIndex = 1035 CustomSections[Sym.ElementIndex].OutputIndex; 1036 encodeULEB128(SectionIndex, W.OS); 1037 break; 1038 } 1039 default: 1040 llvm_unreachable("unexpected kind"); 1041 } 1042 } 1043 endSection(SubSection); 1044 } 1045 1046 if (DataSegments.size()) { 1047 startSection(SubSection, wasm::WASM_SEGMENT_INFO); 1048 encodeULEB128(DataSegments.size(), W.OS); 1049 for (const WasmDataSegment &Segment : DataSegments) { 1050 writeString(Segment.Name); 1051 encodeULEB128(Segment.Alignment, W.OS); 1052 encodeULEB128(Segment.LinkerFlags, W.OS); 1053 } 1054 endSection(SubSection); 1055 } 1056 1057 if (!InitFuncs.empty()) { 1058 startSection(SubSection, wasm::WASM_INIT_FUNCS); 1059 encodeULEB128(InitFuncs.size(), W.OS); 1060 for (auto &StartFunc : InitFuncs) { 1061 encodeULEB128(StartFunc.first, W.OS); // priority 1062 encodeULEB128(StartFunc.second, W.OS); // function index 1063 } 1064 endSection(SubSection); 1065 } 1066 1067 if (Comdats.size()) { 1068 startSection(SubSection, wasm::WASM_COMDAT_INFO); 1069 encodeULEB128(Comdats.size(), W.OS); 1070 for (const auto &C : Comdats) { 1071 writeString(C.first); 1072 encodeULEB128(0, W.OS); // flags for future use 1073 encodeULEB128(C.second.size(), W.OS); 1074 for (const WasmComdatEntry &Entry : C.second) { 1075 encodeULEB128(Entry.Kind, W.OS); 1076 encodeULEB128(Entry.Index, W.OS); 1077 } 1078 } 1079 endSection(SubSection); 1080 } 1081 1082 endSection(Section); 1083 } 1084 1085 void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection, 1086 const MCAssembler &Asm, 1087 const MCAsmLayout &Layout) { 1088 SectionBookkeeping Section; 1089 auto *Sec = CustomSection.Section; 1090 startCustomSection(Section, CustomSection.Name); 1091 1092 Sec->setSectionOffset(W.OS.tell() - Section.ContentsOffset); 1093 Asm.writeSectionData(W.OS, Sec, Layout); 1094 1095 CustomSection.OutputContentsOffset = Section.ContentsOffset; 1096 CustomSection.OutputIndex = Section.Index; 1097 1098 endSection(Section); 1099 1100 // Apply fixups. 1101 auto &Relocations = CustomSectionsRelocations[CustomSection.Section]; 1102 applyRelocations(Relocations, CustomSection.OutputContentsOffset, Layout); 1103 } 1104 1105 uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) { 1106 assert(Symbol.isFunction()); 1107 assert(TypeIndices.count(&Symbol)); 1108 return TypeIndices[&Symbol]; 1109 } 1110 1111 uint32_t WasmObjectWriter::getEventType(const MCSymbolWasm &Symbol) { 1112 assert(Symbol.isEvent()); 1113 assert(TypeIndices.count(&Symbol)); 1114 return TypeIndices[&Symbol]; 1115 } 1116 1117 void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) { 1118 assert(Symbol.isFunction()); 1119 1120 WasmSignature S; 1121 1122 if (auto *Sig = Symbol.getSignature()) { 1123 S.Returns = Sig->Returns; 1124 S.Params = Sig->Params; 1125 } 1126 1127 auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size())); 1128 if (Pair.second) 1129 Signatures.push_back(S); 1130 TypeIndices[&Symbol] = Pair.first->second; 1131 1132 LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol 1133 << " new:" << Pair.second << "\n"); 1134 LLVM_DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n"); 1135 } 1136 1137 void WasmObjectWriter::registerEventType(const MCSymbolWasm &Symbol) { 1138 assert(Symbol.isEvent()); 1139 1140 // TODO Currently we don't generate imported exceptions, but if we do, we 1141 // should have a way of infering types of imported exceptions. 1142 WasmSignature S; 1143 if (auto *Sig = Symbol.getSignature()) { 1144 S.Returns = Sig->Returns; 1145 S.Params = Sig->Params; 1146 } 1147 1148 auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size())); 1149 if (Pair.second) 1150 Signatures.push_back(S); 1151 TypeIndices[&Symbol] = Pair.first->second; 1152 1153 LLVM_DEBUG(dbgs() << "registerEventType: " << Symbol << " new:" << Pair.second 1154 << "\n"); 1155 LLVM_DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n"); 1156 } 1157 1158 static bool isInSymtab(const MCSymbolWasm &Sym) { 1159 if (Sym.isUsedInReloc() || Sym.isUsedInInitArray()) 1160 return true; 1161 1162 if (Sym.isComdat() && !Sym.isDefined()) 1163 return false; 1164 1165 if (Sym.isTemporary()) 1166 return false; 1167 1168 if (Sym.isSection()) 1169 return false; 1170 1171 return true; 1172 } 1173 1174 uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm, 1175 const MCAsmLayout &Layout) { 1176 uint64_t StartOffset = W.OS.tell(); 1177 1178 LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n"); 1179 1180 // Collect information from the available symbols. 1181 SmallVector<WasmFunction, 4> Functions; 1182 SmallVector<uint32_t, 4> TableElems; 1183 SmallVector<wasm::WasmImport, 4> Imports; 1184 SmallVector<wasm::WasmExport, 4> Exports; 1185 SmallVector<wasm::WasmEventType, 1> Events; 1186 SmallVector<wasm::WasmGlobal, 1> Globals; 1187 SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos; 1188 SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs; 1189 std::map<StringRef, std::vector<WasmComdatEntry>> Comdats; 1190 uint32_t DataSize = 0; 1191 1192 // For now, always emit the memory import, since loads and stores are not 1193 // valid without it. In the future, we could perhaps be more clever and omit 1194 // it if there are no loads or stores. 1195 wasm::WasmImport MemImport; 1196 MemImport.Module = "env"; 1197 MemImport.Field = "__linear_memory"; 1198 MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY; 1199 Imports.push_back(MemImport); 1200 1201 // For now, always emit the table section, since indirect calls are not 1202 // valid without it. In the future, we could perhaps be more clever and omit 1203 // it if there are no indirect calls. 1204 wasm::WasmImport TableImport; 1205 TableImport.Module = "env"; 1206 TableImport.Field = "__indirect_function_table"; 1207 TableImport.Kind = wasm::WASM_EXTERNAL_TABLE; 1208 TableImport.Table.ElemType = wasm::WASM_TYPE_FUNCREF; 1209 Imports.push_back(TableImport); 1210 1211 // Populate SignatureIndices, and Imports and WasmIndices for undefined 1212 // symbols. This must be done before populating WasmIndices for defined 1213 // symbols. 1214 for (const MCSymbol &S : Asm.symbols()) { 1215 const auto &WS = static_cast<const MCSymbolWasm &>(S); 1216 1217 // Register types for all functions, including those with private linkage 1218 // (because wasm always needs a type signature). 1219 if (WS.isFunction()) { 1220 const MCSymbolWasm *Base = cast<MCSymbolWasm>(Layout.getBaseSymbol(S)); 1221 registerFunctionType(*Base); 1222 } 1223 1224 if (WS.isEvent()) 1225 registerEventType(WS); 1226 1227 if (WS.isTemporary()) 1228 continue; 1229 1230 // If the symbol is not defined in this translation unit, import it. 1231 if (!WS.isDefined() && !WS.isComdat()) { 1232 if (WS.isFunction()) { 1233 wasm::WasmImport Import; 1234 Import.Module = WS.getImportModule(); 1235 Import.Field = WS.getImportName(); 1236 Import.Kind = wasm::WASM_EXTERNAL_FUNCTION; 1237 Import.SigIndex = getFunctionType(WS); 1238 Imports.push_back(Import); 1239 assert(WasmIndices.count(&WS) == 0); 1240 WasmIndices[&WS] = NumFunctionImports++; 1241 } else if (WS.isGlobal()) { 1242 if (WS.isWeak()) 1243 report_fatal_error("undefined global symbol cannot be weak"); 1244 1245 wasm::WasmImport Import; 1246 Import.Field = WS.getImportName(); 1247 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL; 1248 Import.Module = WS.getImportModule(); 1249 Import.Global = WS.getGlobalType(); 1250 Imports.push_back(Import); 1251 assert(WasmIndices.count(&WS) == 0); 1252 WasmIndices[&WS] = NumGlobalImports++; 1253 } else if (WS.isEvent()) { 1254 if (WS.isWeak()) 1255 report_fatal_error("undefined event symbol cannot be weak"); 1256 1257 wasm::WasmImport Import; 1258 Import.Module = WS.getImportModule(); 1259 Import.Field = WS.getImportName(); 1260 Import.Kind = wasm::WASM_EXTERNAL_EVENT; 1261 Import.Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION; 1262 Import.Event.SigIndex = getEventType(WS); 1263 Imports.push_back(Import); 1264 assert(WasmIndices.count(&WS) == 0); 1265 WasmIndices[&WS] = NumEventImports++; 1266 } 1267 } 1268 } 1269 1270 // Add imports for GOT globals 1271 for (const MCSymbol &S : Asm.symbols()) { 1272 const auto &WS = static_cast<const MCSymbolWasm &>(S); 1273 if (WS.isUsedInGOT()) { 1274 wasm::WasmImport Import; 1275 if (WS.isFunction()) 1276 Import.Module = "GOT.func"; 1277 else 1278 Import.Module = "GOT.mem"; 1279 Import.Field = WS.getName(); 1280 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL; 1281 Import.Global = {wasm::WASM_TYPE_I32, true}; 1282 Imports.push_back(Import); 1283 assert(GOTIndices.count(&WS) == 0); 1284 GOTIndices[&WS] = NumGlobalImports++; 1285 } 1286 } 1287 1288 // Populate DataSegments and CustomSections, which must be done before 1289 // populating DataLocations. 1290 for (MCSection &Sec : Asm) { 1291 auto &Section = static_cast<MCSectionWasm &>(Sec); 1292 StringRef SectionName = Section.getName(); 1293 1294 // .init_array sections are handled specially elsewhere. 1295 if (SectionName.startswith(".init_array")) 1296 continue; 1297 1298 // Code is handled separately 1299 if (Section.getKind().isText()) 1300 continue; 1301 1302 if (Section.isWasmData()) { 1303 uint32_t SegmentIndex = DataSegments.size(); 1304 DataSize = alignTo(DataSize, Section.getAlignment()); 1305 DataSegments.emplace_back(); 1306 WasmDataSegment &Segment = DataSegments.back(); 1307 Segment.Name = SectionName; 1308 Segment.InitFlags = 1309 Section.getPassive() ? (uint32_t)wasm::WASM_SEGMENT_IS_PASSIVE : 0; 1310 Segment.Offset = DataSize; 1311 Segment.Section = &Section; 1312 addData(Segment.Data, Section); 1313 Segment.Alignment = Log2_32(Section.getAlignment()); 1314 Segment.LinkerFlags = 0; 1315 DataSize += Segment.Data.size(); 1316 Section.setSegmentIndex(SegmentIndex); 1317 1318 if (const MCSymbolWasm *C = Section.getGroup()) { 1319 Comdats[C->getName()].emplace_back( 1320 WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex}); 1321 } 1322 } else { 1323 // Create custom sections 1324 assert(Sec.getKind().isMetadata()); 1325 1326 StringRef Name = SectionName; 1327 1328 // For user-defined custom sections, strip the prefix 1329 if (Name.startswith(".custom_section.")) 1330 Name = Name.substr(strlen(".custom_section.")); 1331 1332 MCSymbol *Begin = Sec.getBeginSymbol(); 1333 if (Begin) { 1334 WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size(); 1335 if (SectionName != Begin->getName()) 1336 report_fatal_error("section name and begin symbol should match: " + 1337 Twine(SectionName)); 1338 } 1339 1340 // Separate out the producers and target features sections 1341 if (Name == "producers") { 1342 ProducersSection = std::make_unique<WasmCustomSection>(Name, &Section); 1343 continue; 1344 } 1345 if (Name == "target_features") { 1346 TargetFeaturesSection = 1347 std::make_unique<WasmCustomSection>(Name, &Section); 1348 continue; 1349 } 1350 1351 CustomSections.emplace_back(Name, &Section); 1352 } 1353 } 1354 1355 // Populate WasmIndices and DataLocations for defined symbols. 1356 for (const MCSymbol &S : Asm.symbols()) { 1357 // Ignore unnamed temporary symbols, which aren't ever exported, imported, 1358 // or used in relocations. 1359 if (S.isTemporary() && S.getName().empty()) 1360 continue; 1361 1362 const auto &WS = static_cast<const MCSymbolWasm &>(S); 1363 LLVM_DEBUG( 1364 dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'" 1365 << " isDefined=" << S.isDefined() << " isExternal=" 1366 << S.isExternal() << " isTemporary=" << S.isTemporary() 1367 << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden() 1368 << " isVariable=" << WS.isVariable() << "\n"); 1369 1370 if (WS.isVariable()) 1371 continue; 1372 if (WS.isComdat() && !WS.isDefined()) 1373 continue; 1374 1375 if (WS.isFunction()) { 1376 unsigned Index; 1377 if (WS.isDefined()) { 1378 if (WS.getOffset() != 0) 1379 report_fatal_error( 1380 "function sections must contain one function each"); 1381 1382 if (WS.getSize() == nullptr) 1383 report_fatal_error( 1384 "function symbols must have a size set with .size"); 1385 1386 // A definition. Write out the function body. 1387 Index = NumFunctionImports + Functions.size(); 1388 WasmFunction Func; 1389 Func.SigIndex = getFunctionType(WS); 1390 Func.Sym = &WS; 1391 WasmIndices[&WS] = Index; 1392 Functions.push_back(Func); 1393 1394 auto &Section = static_cast<MCSectionWasm &>(WS.getSection()); 1395 if (const MCSymbolWasm *C = Section.getGroup()) { 1396 Comdats[C->getName()].emplace_back( 1397 WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index}); 1398 } 1399 1400 if (WS.hasExportName()) { 1401 wasm::WasmExport Export; 1402 Export.Name = WS.getExportName(); 1403 Export.Kind = wasm::WASM_EXTERNAL_FUNCTION; 1404 Export.Index = Index; 1405 Exports.push_back(Export); 1406 } 1407 } else { 1408 // An import; the index was assigned above. 1409 Index = WasmIndices.find(&WS)->second; 1410 } 1411 1412 LLVM_DEBUG(dbgs() << " -> function index: " << Index << "\n"); 1413 1414 } else if (WS.isData()) { 1415 if (!isInSymtab(WS)) 1416 continue; 1417 1418 if (!WS.isDefined()) { 1419 LLVM_DEBUG(dbgs() << " -> segment index: -1" 1420 << "\n"); 1421 continue; 1422 } 1423 1424 if (!WS.getSize()) 1425 report_fatal_error("data symbols must have a size set with .size: " + 1426 WS.getName()); 1427 1428 int64_t Size = 0; 1429 if (!WS.getSize()->evaluateAsAbsolute(Size, Layout)) 1430 report_fatal_error(".size expression must be evaluatable"); 1431 1432 auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection()); 1433 if (!DataSection.isWasmData()) 1434 report_fatal_error("data symbols must live in a data section: " + 1435 WS.getName()); 1436 1437 // For each data symbol, export it in the symtab as a reference to the 1438 // corresponding Wasm data segment. 1439 wasm::WasmDataReference Ref = wasm::WasmDataReference{ 1440 DataSection.getSegmentIndex(), Layout.getSymbolOffset(WS), 1441 static_cast<uint64_t>(Size)}; 1442 DataLocations[&WS] = Ref; 1443 LLVM_DEBUG(dbgs() << " -> segment index: " << Ref.Segment << "\n"); 1444 1445 } else if (WS.isGlobal()) { 1446 // A "true" Wasm global (currently just __stack_pointer) 1447 if (WS.isDefined()) { 1448 assert(WasmIndices.count(&WS) == 0); 1449 wasm::WasmGlobal Global; 1450 Global.Type = WS.getGlobalType(); 1451 Global.Index = NumGlobalImports + Globals.size(); 1452 switch (Global.Type.Type) { 1453 case wasm::WASM_TYPE_I32: 1454 Global.InitExpr.Opcode = wasm::WASM_OPCODE_I32_CONST; 1455 break; 1456 case wasm::WASM_TYPE_I64: 1457 Global.InitExpr.Opcode = wasm::WASM_OPCODE_I64_CONST; 1458 break; 1459 case wasm::WASM_TYPE_F32: 1460 Global.InitExpr.Opcode = wasm::WASM_OPCODE_F32_CONST; 1461 break; 1462 case wasm::WASM_TYPE_F64: 1463 Global.InitExpr.Opcode = wasm::WASM_OPCODE_F64_CONST; 1464 break; 1465 default: 1466 llvm_unreachable("unexpected type"); 1467 } 1468 WasmIndices[&WS] = Global.Index; 1469 Globals.push_back(Global); 1470 } else { 1471 // An import; the index was assigned above 1472 LLVM_DEBUG(dbgs() << " -> global index: " 1473 << WasmIndices.find(&WS)->second << "\n"); 1474 } 1475 } else if (WS.isEvent()) { 1476 // C++ exception symbol (__cpp_exception) 1477 unsigned Index; 1478 if (WS.isDefined()) { 1479 assert(WasmIndices.count(&WS) == 0); 1480 Index = NumEventImports + Events.size(); 1481 wasm::WasmEventType Event; 1482 Event.SigIndex = getEventType(WS); 1483 Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION; 1484 WasmIndices[&WS] = Index; 1485 Events.push_back(Event); 1486 } else { 1487 // An import; the index was assigned above. 1488 assert(WasmIndices.count(&WS) > 0); 1489 } 1490 LLVM_DEBUG(dbgs() << " -> event index: " << WasmIndices.find(&WS)->second 1491 << "\n"); 1492 1493 } else { 1494 assert(WS.isSection()); 1495 } 1496 } 1497 1498 // Populate WasmIndices and DataLocations for aliased symbols. We need to 1499 // process these in a separate pass because we need to have processed the 1500 // target of the alias before the alias itself and the symbols are not 1501 // necessarily ordered in this way. 1502 for (const MCSymbol &S : Asm.symbols()) { 1503 if (!S.isVariable()) 1504 continue; 1505 1506 assert(S.isDefined()); 1507 1508 const MCSymbolWasm *Base = cast<MCSymbolWasm>(Layout.getBaseSymbol(S)); 1509 1510 // Find the target symbol of this weak alias and export that index 1511 const auto &WS = static_cast<const MCSymbolWasm &>(S); 1512 LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *Base << "'\n"); 1513 1514 if (Base->isFunction()) { 1515 assert(WasmIndices.count(Base) > 0); 1516 uint32_t WasmIndex = WasmIndices.find(Base)->second; 1517 assert(WasmIndices.count(&WS) == 0); 1518 WasmIndices[&WS] = WasmIndex; 1519 LLVM_DEBUG(dbgs() << " -> index:" << WasmIndex << "\n"); 1520 } else if (Base->isData()) { 1521 auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection()); 1522 uint64_t Offset = Layout.getSymbolOffset(S); 1523 int64_t Size = 0; 1524 // For data symbol alias we use the size of the base symbol as the 1525 // size of the alias. When an offset from the base is involved this 1526 // can result in a offset + size goes past the end of the data section 1527 // which out object format doesn't support. So we must clamp it. 1528 if (!Base->getSize()->evaluateAsAbsolute(Size, Layout)) 1529 report_fatal_error(".size expression must be evaluatable"); 1530 const WasmDataSegment &Segment = 1531 DataSegments[DataSection.getSegmentIndex()]; 1532 Size = 1533 std::min(static_cast<uint64_t>(Size), Segment.Data.size() - Offset); 1534 wasm::WasmDataReference Ref = wasm::WasmDataReference{ 1535 DataSection.getSegmentIndex(), 1536 static_cast<uint32_t>(Layout.getSymbolOffset(S)), 1537 static_cast<uint32_t>(Size)}; 1538 DataLocations[&WS] = Ref; 1539 LLVM_DEBUG(dbgs() << " -> index:" << Ref.Segment << "\n"); 1540 } else { 1541 report_fatal_error("don't yet support global/event aliases"); 1542 } 1543 } 1544 1545 // Finally, populate the symbol table itself, in its "natural" order. 1546 for (const MCSymbol &S : Asm.symbols()) { 1547 const auto &WS = static_cast<const MCSymbolWasm &>(S); 1548 if (!isInSymtab(WS)) { 1549 WS.setIndex(InvalidIndex); 1550 continue; 1551 } 1552 LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n"); 1553 1554 uint32_t Flags = 0; 1555 if (WS.isWeak()) 1556 Flags |= wasm::WASM_SYMBOL_BINDING_WEAK; 1557 if (WS.isHidden()) 1558 Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN; 1559 if (!WS.isExternal() && WS.isDefined()) 1560 Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL; 1561 if (WS.isUndefined()) 1562 Flags |= wasm::WASM_SYMBOL_UNDEFINED; 1563 if (WS.isNoStrip()) { 1564 Flags |= wasm::WASM_SYMBOL_NO_STRIP; 1565 if (isEmscripten()) { 1566 Flags |= wasm::WASM_SYMBOL_EXPORTED; 1567 } 1568 } 1569 if (WS.hasImportName()) 1570 Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME; 1571 if (WS.hasExportName()) 1572 Flags |= wasm::WASM_SYMBOL_EXPORTED; 1573 1574 wasm::WasmSymbolInfo Info; 1575 Info.Name = WS.getName(); 1576 Info.Kind = WS.getType(); 1577 Info.Flags = Flags; 1578 if (!WS.isData()) { 1579 assert(WasmIndices.count(&WS) > 0); 1580 Info.ElementIndex = WasmIndices.find(&WS)->second; 1581 } else if (WS.isDefined()) { 1582 assert(DataLocations.count(&WS) > 0); 1583 Info.DataRef = DataLocations.find(&WS)->second; 1584 } 1585 WS.setIndex(SymbolInfos.size()); 1586 SymbolInfos.emplace_back(Info); 1587 } 1588 1589 { 1590 auto HandleReloc = [&](const WasmRelocationEntry &Rel) { 1591 // Functions referenced by a relocation need to put in the table. This is 1592 // purely to make the object file's provisional values readable, and is 1593 // ignored by the linker, which re-calculates the relocations itself. 1594 if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 && 1595 Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB && 1596 Rel.Type != wasm::R_WASM_TABLE_INDEX_REL_SLEB) 1597 return; 1598 assert(Rel.Symbol->isFunction()); 1599 const MCSymbolWasm *Base = 1600 cast<MCSymbolWasm>(Layout.getBaseSymbol(*Rel.Symbol)); 1601 uint32_t FunctionIndex = WasmIndices.find(Base)->second; 1602 uint32_t TableIndex = TableElems.size() + InitialTableOffset; 1603 if (TableIndices.try_emplace(Base, TableIndex).second) { 1604 LLVM_DEBUG(dbgs() << " -> adding " << Base->getName() 1605 << " to table: " << TableIndex << "\n"); 1606 TableElems.push_back(FunctionIndex); 1607 registerFunctionType(*Base); 1608 } 1609 }; 1610 1611 for (const WasmRelocationEntry &RelEntry : CodeRelocations) 1612 HandleReloc(RelEntry); 1613 for (const WasmRelocationEntry &RelEntry : DataRelocations) 1614 HandleReloc(RelEntry); 1615 } 1616 1617 // Translate .init_array section contents into start functions. 1618 for (const MCSection &S : Asm) { 1619 const auto &WS = static_cast<const MCSectionWasm &>(S); 1620 if (WS.getName().startswith(".fini_array")) 1621 report_fatal_error(".fini_array sections are unsupported"); 1622 if (!WS.getName().startswith(".init_array")) 1623 continue; 1624 if (WS.getFragmentList().empty()) 1625 continue; 1626 1627 // init_array is expected to contain a single non-empty data fragment 1628 if (WS.getFragmentList().size() != 3) 1629 report_fatal_error("only one .init_array section fragment supported"); 1630 1631 auto IT = WS.begin(); 1632 const MCFragment &EmptyFrag = *IT; 1633 if (EmptyFrag.getKind() != MCFragment::FT_Data) 1634 report_fatal_error(".init_array section should be aligned"); 1635 1636 IT = std::next(IT); 1637 const MCFragment &AlignFrag = *IT; 1638 if (AlignFrag.getKind() != MCFragment::FT_Align) 1639 report_fatal_error(".init_array section should be aligned"); 1640 if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4)) 1641 report_fatal_error(".init_array section should be aligned for pointers"); 1642 1643 const MCFragment &Frag = *std::next(IT); 1644 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data) 1645 report_fatal_error("only data supported in .init_array section"); 1646 1647 uint16_t Priority = UINT16_MAX; 1648 unsigned PrefixLength = strlen(".init_array"); 1649 if (WS.getName().size() > PrefixLength) { 1650 if (WS.getName()[PrefixLength] != '.') 1651 report_fatal_error( 1652 ".init_array section priority should start with '.'"); 1653 if (WS.getName().substr(PrefixLength + 1).getAsInteger(10, Priority)) 1654 report_fatal_error("invalid .init_array section priority"); 1655 } 1656 const auto &DataFrag = cast<MCDataFragment>(Frag); 1657 const SmallVectorImpl<char> &Contents = DataFrag.getContents(); 1658 for (const uint8_t * 1659 P = (const uint8_t *)Contents.data(), 1660 *End = (const uint8_t *)Contents.data() + Contents.size(); 1661 P != End; ++P) { 1662 if (*P != 0) 1663 report_fatal_error("non-symbolic data in .init_array section"); 1664 } 1665 for (const MCFixup &Fixup : DataFrag.getFixups()) { 1666 assert(Fixup.getKind() == 1667 MCFixup::getKindForSize(is64Bit() ? 8 : 4, false)); 1668 const MCExpr *Expr = Fixup.getValue(); 1669 auto *SymRef = dyn_cast<MCSymbolRefExpr>(Expr); 1670 if (!SymRef) 1671 report_fatal_error("fixups in .init_array should be symbol references"); 1672 const auto &TargetSym = cast<const MCSymbolWasm>(SymRef->getSymbol()); 1673 if (TargetSym.getIndex() == InvalidIndex) 1674 report_fatal_error("symbols in .init_array should exist in symtab"); 1675 if (!TargetSym.isFunction()) 1676 report_fatal_error("symbols in .init_array should be for functions"); 1677 InitFuncs.push_back( 1678 std::make_pair(Priority, TargetSym.getIndex())); 1679 } 1680 } 1681 1682 // Write out the Wasm header. 1683 writeHeader(Asm); 1684 1685 writeTypeSection(Signatures); 1686 writeImportSection(Imports, DataSize, TableElems.size()); 1687 writeFunctionSection(Functions); 1688 // Skip the "table" section; we import the table instead. 1689 // Skip the "memory" section; we import the memory instead. 1690 writeEventSection(Events); 1691 writeGlobalSection(Globals); 1692 writeExportSection(Exports); 1693 writeElemSection(TableElems); 1694 writeDataCountSection(); 1695 writeCodeSection(Asm, Layout, Functions); 1696 writeDataSection(Layout); 1697 for (auto &CustomSection : CustomSections) 1698 writeCustomSection(CustomSection, Asm, Layout); 1699 writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats); 1700 writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations); 1701 writeRelocSection(DataSectionIndex, "DATA", DataRelocations); 1702 writeCustomRelocSections(); 1703 if (ProducersSection) 1704 writeCustomSection(*ProducersSection, Asm, Layout); 1705 if (TargetFeaturesSection) 1706 writeCustomSection(*TargetFeaturesSection, Asm, Layout); 1707 1708 // TODO: Translate the .comment section to the output. 1709 return W.OS.tell() - StartOffset; 1710 } 1711 1712 std::unique_ptr<MCObjectWriter> 1713 llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW, 1714 raw_pwrite_stream &OS) { 1715 return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS); 1716 } 1717