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