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