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