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 writeDataCountSection(); 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 = TargetObjectWriter->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 if (RefA->getKind() == MCSymbolRefExpr::VK_GOT) 547 SymA->setUsedInGOT(); 548 549 WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection); 550 LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n"); 551 552 if (FixupSection.isWasmData()) { 553 DataRelocations.push_back(Rec); 554 } else if (FixupSection.getKind().isText()) { 555 CodeRelocations.push_back(Rec); 556 } else if (FixupSection.getKind().isMetadata()) { 557 CustomSectionsRelocations[&FixupSection].push_back(Rec); 558 } else { 559 llvm_unreachable("unexpected section type"); 560 } 561 } 562 563 static const MCSymbolWasm *resolveSymbol(const MCSymbolWasm &Symbol) { 564 const MCSymbolWasm* Ret = &Symbol; 565 while (Ret->isVariable()) { 566 const MCExpr *Expr = Ret->getVariableValue(); 567 auto *Inner = cast<MCSymbolRefExpr>(Expr); 568 Ret = cast<MCSymbolWasm>(&Inner->getSymbol()); 569 } 570 return Ret; 571 } 572 573 // Compute a value to write into the code at the location covered 574 // by RelEntry. This value isn't used by the static linker; it just serves 575 // to make the object format more readable and more likely to be directly 576 // useable. 577 uint32_t 578 WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) { 579 if (RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_LEB && !RelEntry.Symbol->isGlobal()) { 580 assert(GOTIndices.count(RelEntry.Symbol) > 0 && "symbol not found in GOT index space"); 581 return GOTIndices[RelEntry.Symbol]; 582 } 583 584 switch (RelEntry.Type) { 585 case wasm::R_WASM_TABLE_INDEX_REL_SLEB: 586 case wasm::R_WASM_TABLE_INDEX_SLEB: 587 case wasm::R_WASM_TABLE_INDEX_I32: { 588 // Provisional value is table address of the resolved symbol itself 589 const MCSymbolWasm *Sym = resolveSymbol(*RelEntry.Symbol); 590 assert(Sym->isFunction()); 591 return TableIndices[Sym]; 592 } 593 case wasm::R_WASM_TYPE_INDEX_LEB: 594 // Provisional value is same as the index 595 return getRelocationIndexValue(RelEntry); 596 case wasm::R_WASM_FUNCTION_INDEX_LEB: 597 case wasm::R_WASM_GLOBAL_INDEX_LEB: 598 case wasm::R_WASM_EVENT_INDEX_LEB: 599 // Provisional value is function/global/event Wasm index 600 assert(WasmIndices.count(RelEntry.Symbol) > 0 && "symbol not found in wasm index space"); 601 return WasmIndices[RelEntry.Symbol]; 602 case wasm::R_WASM_FUNCTION_OFFSET_I32: 603 case wasm::R_WASM_SECTION_OFFSET_I32: { 604 const auto &Section = 605 static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection()); 606 return Section.getSectionOffset() + RelEntry.Addend; 607 } 608 case wasm::R_WASM_MEMORY_ADDR_LEB: 609 case wasm::R_WASM_MEMORY_ADDR_I32: 610 case wasm::R_WASM_MEMORY_ADDR_REL_SLEB: 611 case wasm::R_WASM_MEMORY_ADDR_SLEB: { 612 // Provisional value is address of the global 613 const MCSymbolWasm *Sym = resolveSymbol(*RelEntry.Symbol); 614 // For undefined symbols, use zero 615 if (!Sym->isDefined()) 616 return 0; 617 const wasm::WasmDataReference &Ref = DataLocations[Sym]; 618 const WasmDataSegment &Segment = DataSegments[Ref.Segment]; 619 // Ignore overflow. LLVM allows address arithmetic to silently wrap. 620 return Segment.Offset + Ref.Offset + RelEntry.Addend; 621 } 622 default: 623 llvm_unreachable("invalid relocation type"); 624 } 625 } 626 627 static void addData(SmallVectorImpl<char> &DataBytes, 628 MCSectionWasm &DataSection) { 629 LLVM_DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n"); 630 631 DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment())); 632 633 for (const MCFragment &Frag : DataSection) { 634 if (Frag.hasInstructions()) 635 report_fatal_error("only data supported in data sections"); 636 637 if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) { 638 if (Align->getValueSize() != 1) 639 report_fatal_error("only byte values supported for alignment"); 640 // If nops are requested, use zeros, as this is the data section. 641 uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue(); 642 uint64_t Size = 643 std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()), 644 DataBytes.size() + Align->getMaxBytesToEmit()); 645 DataBytes.resize(Size, Value); 646 } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) { 647 int64_t NumValues; 648 if (!Fill->getNumValues().evaluateAsAbsolute(NumValues)) 649 llvm_unreachable("The fill should be an assembler constant"); 650 DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues, 651 Fill->getValue()); 652 } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) { 653 const SmallVectorImpl<char> &Contents = LEB->getContents(); 654 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end()); 655 } else { 656 const auto &DataFrag = cast<MCDataFragment>(Frag); 657 const SmallVectorImpl<char> &Contents = DataFrag.getContents(); 658 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end()); 659 } 660 } 661 662 LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n"); 663 } 664 665 uint32_t 666 WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) { 667 if (RelEntry.Type == wasm::R_WASM_TYPE_INDEX_LEB) { 668 if (!TypeIndices.count(RelEntry.Symbol)) 669 report_fatal_error("symbol not found in type index space: " + 670 RelEntry.Symbol->getName()); 671 return TypeIndices[RelEntry.Symbol]; 672 } 673 674 return RelEntry.Symbol->getIndex(); 675 } 676 677 // Apply the portions of the relocation records that we can handle ourselves 678 // directly. 679 void WasmObjectWriter::applyRelocations( 680 ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) { 681 auto &Stream = static_cast<raw_pwrite_stream &>(W.OS); 682 for (const WasmRelocationEntry &RelEntry : Relocations) { 683 uint64_t Offset = ContentsOffset + 684 RelEntry.FixupSection->getSectionOffset() + 685 RelEntry.Offset; 686 687 LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n"); 688 uint32_t Value = getProvisionalValue(RelEntry); 689 690 switch (RelEntry.Type) { 691 case wasm::R_WASM_FUNCTION_INDEX_LEB: 692 case wasm::R_WASM_TYPE_INDEX_LEB: 693 case wasm::R_WASM_GLOBAL_INDEX_LEB: 694 case wasm::R_WASM_MEMORY_ADDR_LEB: 695 case wasm::R_WASM_EVENT_INDEX_LEB: 696 writePatchableLEB(Stream, Value, Offset); 697 break; 698 case wasm::R_WASM_TABLE_INDEX_I32: 699 case wasm::R_WASM_MEMORY_ADDR_I32: 700 case wasm::R_WASM_FUNCTION_OFFSET_I32: 701 case wasm::R_WASM_SECTION_OFFSET_I32: 702 writeI32(Stream, Value, Offset); 703 break; 704 case wasm::R_WASM_TABLE_INDEX_SLEB: 705 case wasm::R_WASM_TABLE_INDEX_REL_SLEB: 706 case wasm::R_WASM_MEMORY_ADDR_SLEB: 707 case wasm::R_WASM_MEMORY_ADDR_REL_SLEB: 708 writePatchableSLEB(Stream, Value, Offset); 709 break; 710 default: 711 llvm_unreachable("invalid relocation type"); 712 } 713 } 714 } 715 716 void WasmObjectWriter::writeTypeSection(ArrayRef<WasmSignature> Signatures) { 717 if (Signatures.empty()) 718 return; 719 720 SectionBookkeeping Section; 721 startSection(Section, wasm::WASM_SEC_TYPE); 722 723 encodeULEB128(Signatures.size(), W.OS); 724 725 for (const WasmSignature &Sig : Signatures) { 726 W.OS << char(wasm::WASM_TYPE_FUNC); 727 encodeULEB128(Sig.Params.size(), W.OS); 728 for (wasm::ValType Ty : Sig.Params) 729 writeValueType(Ty); 730 encodeULEB128(Sig.Returns.size(), W.OS); 731 for (wasm::ValType Ty : Sig.Returns) 732 writeValueType(Ty); 733 } 734 735 endSection(Section); 736 } 737 738 void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports, 739 uint32_t DataSize, 740 uint32_t NumElements) { 741 if (Imports.empty()) 742 return; 743 744 uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize; 745 746 SectionBookkeeping Section; 747 startSection(Section, wasm::WASM_SEC_IMPORT); 748 749 encodeULEB128(Imports.size(), W.OS); 750 for (const wasm::WasmImport &Import : Imports) { 751 writeString(Import.Module); 752 writeString(Import.Field); 753 W.OS << char(Import.Kind); 754 755 switch (Import.Kind) { 756 case wasm::WASM_EXTERNAL_FUNCTION: 757 encodeULEB128(Import.SigIndex, W.OS); 758 break; 759 case wasm::WASM_EXTERNAL_GLOBAL: 760 W.OS << char(Import.Global.Type); 761 W.OS << char(Import.Global.Mutable ? 1 : 0); 762 break; 763 case wasm::WASM_EXTERNAL_MEMORY: 764 encodeULEB128(0, W.OS); // flags 765 encodeULEB128(NumPages, W.OS); // initial 766 break; 767 case wasm::WASM_EXTERNAL_TABLE: 768 W.OS << char(Import.Table.ElemType); 769 encodeULEB128(0, W.OS); // flags 770 encodeULEB128(NumElements, W.OS); // initial 771 break; 772 case wasm::WASM_EXTERNAL_EVENT: 773 encodeULEB128(Import.Event.Attribute, W.OS); 774 encodeULEB128(Import.Event.SigIndex, W.OS); 775 break; 776 default: 777 llvm_unreachable("unsupported import kind"); 778 } 779 } 780 781 endSection(Section); 782 } 783 784 void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) { 785 if (Functions.empty()) 786 return; 787 788 SectionBookkeeping Section; 789 startSection(Section, wasm::WASM_SEC_FUNCTION); 790 791 encodeULEB128(Functions.size(), W.OS); 792 for (const WasmFunction &Func : Functions) 793 encodeULEB128(Func.SigIndex, W.OS); 794 795 endSection(Section); 796 } 797 798 void WasmObjectWriter::writeEventSection(ArrayRef<wasm::WasmEventType> Events) { 799 if (Events.empty()) 800 return; 801 802 SectionBookkeeping Section; 803 startSection(Section, wasm::WASM_SEC_EVENT); 804 805 encodeULEB128(Events.size(), W.OS); 806 for (const wasm::WasmEventType &Event : Events) { 807 encodeULEB128(Event.Attribute, W.OS); 808 encodeULEB128(Event.SigIndex, W.OS); 809 } 810 811 endSection(Section); 812 } 813 814 void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) { 815 if (Exports.empty()) 816 return; 817 818 SectionBookkeeping Section; 819 startSection(Section, wasm::WASM_SEC_EXPORT); 820 821 encodeULEB128(Exports.size(), W.OS); 822 for (const wasm::WasmExport &Export : Exports) { 823 writeString(Export.Name); 824 W.OS << char(Export.Kind); 825 encodeULEB128(Export.Index, W.OS); 826 } 827 828 endSection(Section); 829 } 830 831 void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) { 832 if (TableElems.empty()) 833 return; 834 835 SectionBookkeeping Section; 836 startSection(Section, wasm::WASM_SEC_ELEM); 837 838 encodeULEB128(1, W.OS); // number of "segments" 839 encodeULEB128(0, W.OS); // the table index 840 841 // init expr for starting offset 842 W.OS << char(wasm::WASM_OPCODE_I32_CONST); 843 encodeSLEB128(InitialTableOffset, W.OS); 844 W.OS << char(wasm::WASM_OPCODE_END); 845 846 encodeULEB128(TableElems.size(), W.OS); 847 for (uint32_t Elem : TableElems) 848 encodeULEB128(Elem, W.OS); 849 850 endSection(Section); 851 } 852 853 void WasmObjectWriter::writeDataCountSection() { 854 if (DataSegments.empty()) 855 return; 856 857 SectionBookkeeping Section; 858 startSection(Section, wasm::WASM_SEC_DATACOUNT); 859 encodeULEB128(DataSegments.size(), W.OS); 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 llvm::stable_sort( 938 Relocs, [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) { 939 return (A.Offset + A.FixupSection->getSectionOffset()) < 940 (B.Offset + B.FixupSection->getSectionOffset()); 941 }); 942 943 SectionBookkeeping Section; 944 startCustomSection(Section, std::string("reloc.") + Name.str()); 945 946 encodeULEB128(SectionIndex, W.OS); 947 encodeULEB128(Relocs.size(), W.OS); 948 for (const WasmRelocationEntry &RelEntry : Relocs) { 949 uint64_t Offset = 950 RelEntry.Offset + RelEntry.FixupSection->getSectionOffset(); 951 uint32_t Index = getRelocationIndexValue(RelEntry); 952 953 W.OS << char(RelEntry.Type); 954 encodeULEB128(Offset, W.OS); 955 encodeULEB128(Index, W.OS); 956 if (RelEntry.hasAddend()) 957 encodeSLEB128(RelEntry.Addend, W.OS); 958 } 959 960 endSection(Section); 961 } 962 963 void WasmObjectWriter::writeCustomRelocSections() { 964 for (const auto &Sec : CustomSections) { 965 auto &Relocations = CustomSectionsRelocations[Sec.Section]; 966 writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations); 967 } 968 } 969 970 void WasmObjectWriter::writeLinkingMetaDataSection( 971 ArrayRef<wasm::WasmSymbolInfo> SymbolInfos, 972 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs, 973 const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) { 974 SectionBookkeeping Section; 975 startCustomSection(Section, "linking"); 976 encodeULEB128(wasm::WasmMetadataVersion, W.OS); 977 978 SectionBookkeeping SubSection; 979 if (SymbolInfos.size() != 0) { 980 startSection(SubSection, wasm::WASM_SYMBOL_TABLE); 981 encodeULEB128(SymbolInfos.size(), W.OS); 982 for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) { 983 encodeULEB128(Sym.Kind, W.OS); 984 encodeULEB128(Sym.Flags, W.OS); 985 switch (Sym.Kind) { 986 case wasm::WASM_SYMBOL_TYPE_FUNCTION: 987 case wasm::WASM_SYMBOL_TYPE_GLOBAL: 988 case wasm::WASM_SYMBOL_TYPE_EVENT: 989 encodeULEB128(Sym.ElementIndex, W.OS); 990 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 || 991 (Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) 992 writeString(Sym.Name); 993 break; 994 case wasm::WASM_SYMBOL_TYPE_DATA: 995 writeString(Sym.Name); 996 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) { 997 encodeULEB128(Sym.DataRef.Segment, W.OS); 998 encodeULEB128(Sym.DataRef.Offset, W.OS); 999 encodeULEB128(Sym.DataRef.Size, W.OS); 1000 } 1001 break; 1002 case wasm::WASM_SYMBOL_TYPE_SECTION: { 1003 const uint32_t SectionIndex = 1004 CustomSections[Sym.ElementIndex].OutputIndex; 1005 encodeULEB128(SectionIndex, W.OS); 1006 break; 1007 } 1008 default: 1009 llvm_unreachable("unexpected kind"); 1010 } 1011 } 1012 endSection(SubSection); 1013 } 1014 1015 if (DataSegments.size()) { 1016 startSection(SubSection, wasm::WASM_SEGMENT_INFO); 1017 encodeULEB128(DataSegments.size(), W.OS); 1018 for (const WasmDataSegment &Segment : DataSegments) { 1019 writeString(Segment.Name); 1020 encodeULEB128(Segment.Alignment, W.OS); 1021 encodeULEB128(Segment.LinkerFlags, W.OS); 1022 } 1023 endSection(SubSection); 1024 } 1025 1026 if (!InitFuncs.empty()) { 1027 startSection(SubSection, wasm::WASM_INIT_FUNCS); 1028 encodeULEB128(InitFuncs.size(), W.OS); 1029 for (auto &StartFunc : InitFuncs) { 1030 encodeULEB128(StartFunc.first, W.OS); // priority 1031 encodeULEB128(StartFunc.second, W.OS); // function index 1032 } 1033 endSection(SubSection); 1034 } 1035 1036 if (Comdats.size()) { 1037 startSection(SubSection, wasm::WASM_COMDAT_INFO); 1038 encodeULEB128(Comdats.size(), W.OS); 1039 for (const auto &C : Comdats) { 1040 writeString(C.first); 1041 encodeULEB128(0, W.OS); // flags for future use 1042 encodeULEB128(C.second.size(), W.OS); 1043 for (const WasmComdatEntry &Entry : C.second) { 1044 encodeULEB128(Entry.Kind, W.OS); 1045 encodeULEB128(Entry.Index, W.OS); 1046 } 1047 } 1048 endSection(SubSection); 1049 } 1050 1051 endSection(Section); 1052 } 1053 1054 void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection, 1055 const MCAssembler &Asm, 1056 const MCAsmLayout &Layout) { 1057 SectionBookkeeping Section; 1058 auto *Sec = CustomSection.Section; 1059 startCustomSection(Section, CustomSection.Name); 1060 1061 Sec->setSectionOffset(W.OS.tell() - Section.ContentsOffset); 1062 Asm.writeSectionData(W.OS, Sec, Layout); 1063 1064 CustomSection.OutputContentsOffset = Section.ContentsOffset; 1065 CustomSection.OutputIndex = Section.Index; 1066 1067 endSection(Section); 1068 1069 // Apply fixups. 1070 auto &Relocations = CustomSectionsRelocations[CustomSection.Section]; 1071 applyRelocations(Relocations, CustomSection.OutputContentsOffset); 1072 } 1073 1074 uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) { 1075 assert(Symbol.isFunction()); 1076 assert(TypeIndices.count(&Symbol)); 1077 return TypeIndices[&Symbol]; 1078 } 1079 1080 uint32_t WasmObjectWriter::getEventType(const MCSymbolWasm &Symbol) { 1081 assert(Symbol.isEvent()); 1082 assert(TypeIndices.count(&Symbol)); 1083 return TypeIndices[&Symbol]; 1084 } 1085 1086 void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) { 1087 assert(Symbol.isFunction()); 1088 1089 WasmSignature S; 1090 const MCSymbolWasm *ResolvedSym = resolveSymbol(Symbol); 1091 if (auto *Sig = ResolvedSym->getSignature()) { 1092 S.Returns = Sig->Returns; 1093 S.Params = Sig->Params; 1094 } 1095 1096 auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size())); 1097 if (Pair.second) 1098 Signatures.push_back(S); 1099 TypeIndices[&Symbol] = Pair.first->second; 1100 1101 LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol 1102 << " new:" << Pair.second << "\n"); 1103 LLVM_DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n"); 1104 } 1105 1106 void WasmObjectWriter::registerEventType(const MCSymbolWasm &Symbol) { 1107 assert(Symbol.isEvent()); 1108 1109 // TODO Currently we don't generate imported exceptions, but if we do, we 1110 // should have a way of infering types of imported exceptions. 1111 WasmSignature S; 1112 if (auto *Sig = Symbol.getSignature()) { 1113 S.Returns = Sig->Returns; 1114 S.Params = Sig->Params; 1115 } 1116 1117 auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size())); 1118 if (Pair.second) 1119 Signatures.push_back(S); 1120 TypeIndices[&Symbol] = Pair.first->second; 1121 1122 LLVM_DEBUG(dbgs() << "registerEventType: " << Symbol << " new:" << Pair.second 1123 << "\n"); 1124 LLVM_DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n"); 1125 } 1126 1127 static bool isInSymtab(const MCSymbolWasm &Sym) { 1128 if (Sym.isUsedInReloc()) 1129 return true; 1130 1131 if (Sym.isComdat() && !Sym.isDefined()) 1132 return false; 1133 1134 if (Sym.isTemporary() && Sym.getName().empty()) 1135 return false; 1136 1137 if (Sym.isTemporary() && Sym.isData() && !Sym.getSize()) 1138 return false; 1139 1140 if (Sym.isSection()) 1141 return false; 1142 1143 return true; 1144 } 1145 1146 uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm, 1147 const MCAsmLayout &Layout) { 1148 uint64_t StartOffset = W.OS.tell(); 1149 1150 LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n"); 1151 1152 // Collect information from the available symbols. 1153 SmallVector<WasmFunction, 4> Functions; 1154 SmallVector<uint32_t, 4> TableElems; 1155 SmallVector<wasm::WasmImport, 4> Imports; 1156 SmallVector<wasm::WasmExport, 4> Exports; 1157 SmallVector<wasm::WasmEventType, 1> Events; 1158 SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos; 1159 SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs; 1160 std::map<StringRef, std::vector<WasmComdatEntry>> Comdats; 1161 uint32_t DataSize = 0; 1162 1163 // For now, always emit the memory import, since loads and stores are not 1164 // valid without it. In the future, we could perhaps be more clever and omit 1165 // it if there are no loads or stores. 1166 wasm::WasmImport MemImport; 1167 MemImport.Module = "env"; 1168 MemImport.Field = "__linear_memory"; 1169 MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY; 1170 Imports.push_back(MemImport); 1171 1172 // For now, always emit the table section, since indirect calls are not 1173 // valid without it. In the future, we could perhaps be more clever and omit 1174 // it if there are no indirect calls. 1175 wasm::WasmImport TableImport; 1176 TableImport.Module = "env"; 1177 TableImport.Field = "__indirect_function_table"; 1178 TableImport.Kind = wasm::WASM_EXTERNAL_TABLE; 1179 TableImport.Table.ElemType = wasm::WASM_TYPE_FUNCREF; 1180 Imports.push_back(TableImport); 1181 1182 // Populate SignatureIndices, and Imports and WasmIndices for undefined 1183 // symbols. This must be done before populating WasmIndices for defined 1184 // symbols. 1185 for (const MCSymbol &S : Asm.symbols()) { 1186 const auto &WS = static_cast<const MCSymbolWasm &>(S); 1187 1188 // Register types for all functions, including those with private linkage 1189 // (because wasm always needs a type signature). 1190 if (WS.isFunction()) 1191 registerFunctionType(WS); 1192 1193 if (WS.isEvent()) 1194 registerEventType(WS); 1195 1196 if (WS.isTemporary()) 1197 continue; 1198 1199 // If the symbol is not defined in this translation unit, import it. 1200 if (!WS.isDefined() && !WS.isComdat()) { 1201 if (WS.isFunction()) { 1202 wasm::WasmImport Import; 1203 Import.Module = WS.getImportModule(); 1204 Import.Field = WS.getImportName(); 1205 Import.Kind = wasm::WASM_EXTERNAL_FUNCTION; 1206 Import.SigIndex = getFunctionType(WS); 1207 Imports.push_back(Import); 1208 assert(WasmIndices.count(&WS) == 0); 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.Field = WS.getImportName(); 1216 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL; 1217 Import.Module = WS.getImportModule(); 1218 Import.Global = WS.getGlobalType(); 1219 Imports.push_back(Import); 1220 assert(WasmIndices.count(&WS) == 0); 1221 WasmIndices[&WS] = NumGlobalImports++; 1222 } else if (WS.isEvent()) { 1223 if (WS.isWeak()) 1224 report_fatal_error("undefined event symbol cannot be weak"); 1225 1226 wasm::WasmImport Import; 1227 Import.Module = WS.getImportModule(); 1228 Import.Field = WS.getImportName(); 1229 Import.Kind = wasm::WASM_EXTERNAL_EVENT; 1230 Import.Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION; 1231 Import.Event.SigIndex = getEventType(WS); 1232 Imports.push_back(Import); 1233 assert(WasmIndices.count(&WS) == 0); 1234 WasmIndices[&WS] = NumEventImports++; 1235 } 1236 } 1237 } 1238 1239 // Add imports for GOT globals 1240 for (const MCSymbol &S : Asm.symbols()) { 1241 const auto &WS = static_cast<const MCSymbolWasm &>(S); 1242 if (WS.isUsedInGOT()) { 1243 wasm::WasmImport Import; 1244 if (WS.isFunction()) 1245 Import.Module = "GOT.func"; 1246 else 1247 Import.Module = "GOT.mem"; 1248 Import.Field = WS.getName(); 1249 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL; 1250 Import.Global = {wasm::WASM_TYPE_I32, true}; 1251 Imports.push_back(Import); 1252 assert(GOTIndices.count(&WS) == 0); 1253 GOTIndices[&WS] = NumGlobalImports++; 1254 } 1255 } 1256 1257 // Populate DataSegments and CustomSections, which must be done before 1258 // populating DataLocations. 1259 for (MCSection &Sec : Asm) { 1260 auto &Section = static_cast<MCSectionWasm &>(Sec); 1261 StringRef SectionName = Section.getSectionName(); 1262 1263 // .init_array sections are handled specially elsewhere. 1264 if (SectionName.startswith(".init_array")) 1265 continue; 1266 1267 // Code is handled separately 1268 if (Section.getKind().isText()) 1269 continue; 1270 1271 if (Section.isWasmData()) { 1272 uint32_t SegmentIndex = DataSegments.size(); 1273 DataSize = alignTo(DataSize, Section.getAlignment()); 1274 DataSegments.emplace_back(); 1275 WasmDataSegment &Segment = DataSegments.back(); 1276 Segment.Name = SectionName; 1277 Segment.InitFlags = 1278 Section.getPassive() ? (uint32_t)wasm::WASM_SEGMENT_IS_PASSIVE : 0; 1279 Segment.Offset = DataSize; 1280 Segment.Section = &Section; 1281 addData(Segment.Data, Section); 1282 Segment.Alignment = Log2_32(Section.getAlignment()); 1283 Segment.LinkerFlags = 0; 1284 DataSize += Segment.Data.size(); 1285 Section.setSegmentIndex(SegmentIndex); 1286 1287 if (const MCSymbolWasm *C = Section.getGroup()) { 1288 Comdats[C->getName()].emplace_back( 1289 WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex}); 1290 } 1291 } else { 1292 // Create custom sections 1293 assert(Sec.getKind().isMetadata()); 1294 1295 StringRef Name = SectionName; 1296 1297 // For user-defined custom sections, strip the prefix 1298 if (Name.startswith(".custom_section.")) 1299 Name = Name.substr(strlen(".custom_section.")); 1300 1301 MCSymbol *Begin = Sec.getBeginSymbol(); 1302 if (Begin) { 1303 WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size(); 1304 if (SectionName != Begin->getName()) 1305 report_fatal_error("section name and begin symbol should match: " + 1306 Twine(SectionName)); 1307 } 1308 1309 // Separate out the producers and target features sections 1310 if (Name == "producers") { 1311 ProducersSection = llvm::make_unique<WasmCustomSection>(Name, &Section); 1312 continue; 1313 } 1314 if (Name == "target_features") { 1315 TargetFeaturesSection = 1316 llvm::make_unique<WasmCustomSection>(Name, &Section); 1317 continue; 1318 } 1319 1320 CustomSections.emplace_back(Name, &Section); 1321 } 1322 } 1323 1324 // Populate WasmIndices and DataLocations for defined symbols. 1325 for (const MCSymbol &S : Asm.symbols()) { 1326 // Ignore unnamed temporary symbols, which aren't ever exported, imported, 1327 // or used in relocations. 1328 if (S.isTemporary() && S.getName().empty()) 1329 continue; 1330 1331 const auto &WS = static_cast<const MCSymbolWasm &>(S); 1332 LLVM_DEBUG( 1333 dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'" 1334 << " isDefined=" << S.isDefined() << " isExternal=" 1335 << S.isExternal() << " isTemporary=" << S.isTemporary() 1336 << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden() 1337 << " isVariable=" << WS.isVariable() << "\n"); 1338 1339 if (WS.isVariable()) 1340 continue; 1341 if (WS.isComdat() && !WS.isDefined()) 1342 continue; 1343 1344 if (WS.isFunction()) { 1345 unsigned Index; 1346 if (WS.isDefined()) { 1347 if (WS.getOffset() != 0) 1348 report_fatal_error( 1349 "function sections must contain one function each"); 1350 1351 if (WS.getSize() == nullptr) 1352 report_fatal_error( 1353 "function symbols must have a size set with .size"); 1354 1355 // A definition. Write out the function body. 1356 Index = NumFunctionImports + Functions.size(); 1357 WasmFunction Func; 1358 Func.SigIndex = getFunctionType(WS); 1359 Func.Sym = &WS; 1360 WasmIndices[&WS] = Index; 1361 Functions.push_back(Func); 1362 1363 auto &Section = static_cast<MCSectionWasm &>(WS.getSection()); 1364 if (const MCSymbolWasm *C = Section.getGroup()) { 1365 Comdats[C->getName()].emplace_back( 1366 WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index}); 1367 } 1368 } else { 1369 // An import; the index was assigned above. 1370 Index = WasmIndices.find(&WS)->second; 1371 } 1372 1373 LLVM_DEBUG(dbgs() << " -> function index: " << Index << "\n"); 1374 1375 } else if (WS.isData()) { 1376 if (!isInSymtab(WS)) 1377 continue; 1378 1379 if (!WS.isDefined()) { 1380 LLVM_DEBUG(dbgs() << " -> segment index: -1" 1381 << "\n"); 1382 continue; 1383 } 1384 1385 if (!WS.getSize()) 1386 report_fatal_error("data symbols must have a size set with .size: " + 1387 WS.getName()); 1388 1389 int64_t Size = 0; 1390 if (!WS.getSize()->evaluateAsAbsolute(Size, Layout)) 1391 report_fatal_error(".size expression must be evaluatable"); 1392 1393 auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection()); 1394 assert(DataSection.isWasmData()); 1395 1396 // For each data symbol, export it in the symtab as a reference to the 1397 // corresponding Wasm data segment. 1398 wasm::WasmDataReference Ref = wasm::WasmDataReference{ 1399 DataSection.getSegmentIndex(), 1400 static_cast<uint32_t>(Layout.getSymbolOffset(WS)), 1401 static_cast<uint32_t>(Size)}; 1402 DataLocations[&WS] = Ref; 1403 LLVM_DEBUG(dbgs() << " -> segment index: " << Ref.Segment << "\n"); 1404 1405 } else if (WS.isGlobal()) { 1406 // A "true" Wasm global (currently just __stack_pointer) 1407 if (WS.isDefined()) 1408 report_fatal_error("don't yet support defined globals"); 1409 1410 // An import; the index was assigned above 1411 LLVM_DEBUG(dbgs() << " -> global index: " 1412 << WasmIndices.find(&WS)->second << "\n"); 1413 1414 } else if (WS.isEvent()) { 1415 // C++ exception symbol (__cpp_exception) 1416 unsigned Index; 1417 if (WS.isDefined()) { 1418 Index = NumEventImports + Events.size(); 1419 wasm::WasmEventType Event; 1420 Event.SigIndex = getEventType(WS); 1421 Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION; 1422 assert(WasmIndices.count(&WS) == 0); 1423 WasmIndices[&WS] = Index; 1424 Events.push_back(Event); 1425 } else { 1426 // An import; the index was assigned above. 1427 assert(WasmIndices.count(&WS) > 0); 1428 Index = WasmIndices.find(&WS)->second; 1429 } 1430 LLVM_DEBUG(dbgs() << " -> event index: " << WasmIndices.find(&WS)->second 1431 << "\n"); 1432 1433 } else { 1434 assert(WS.isSection()); 1435 } 1436 } 1437 1438 // Populate WasmIndices and DataLocations for aliased symbols. We need to 1439 // process these in a separate pass because we need to have processed the 1440 // target of the alias before the alias itself and the symbols are not 1441 // necessarily ordered in this way. 1442 for (const MCSymbol &S : Asm.symbols()) { 1443 if (!S.isVariable()) 1444 continue; 1445 1446 assert(S.isDefined()); 1447 1448 // Find the target symbol of this weak alias and export that index 1449 const auto &WS = static_cast<const MCSymbolWasm &>(S); 1450 const MCSymbolWasm *ResolvedSym = resolveSymbol(WS); 1451 LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym 1452 << "'\n"); 1453 1454 if (ResolvedSym->isFunction()) { 1455 assert(WasmIndices.count(ResolvedSym) > 0); 1456 uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second; 1457 assert(WasmIndices.count(&WS) == 0); 1458 WasmIndices[&WS] = WasmIndex; 1459 LLVM_DEBUG(dbgs() << " -> index:" << WasmIndex << "\n"); 1460 } else if (ResolvedSym->isData()) { 1461 assert(DataLocations.count(ResolvedSym) > 0); 1462 const wasm::WasmDataReference &Ref = 1463 DataLocations.find(ResolvedSym)->second; 1464 DataLocations[&WS] = Ref; 1465 LLVM_DEBUG(dbgs() << " -> index:" << Ref.Segment << "\n"); 1466 } else { 1467 report_fatal_error("don't yet support global/event aliases"); 1468 } 1469 } 1470 1471 // Finally, populate the symbol table itself, in its "natural" order. 1472 for (const MCSymbol &S : Asm.symbols()) { 1473 const auto &WS = static_cast<const MCSymbolWasm &>(S); 1474 if (!isInSymtab(WS)) { 1475 WS.setIndex(InvalidIndex); 1476 continue; 1477 } 1478 LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n"); 1479 1480 uint32_t Flags = 0; 1481 if (WS.isWeak()) 1482 Flags |= wasm::WASM_SYMBOL_BINDING_WEAK; 1483 if (WS.isHidden()) 1484 Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN; 1485 if (!WS.isExternal() && WS.isDefined()) 1486 Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL; 1487 if (WS.isUndefined()) 1488 Flags |= wasm::WASM_SYMBOL_UNDEFINED; 1489 if (WS.isExported()) 1490 Flags |= wasm::WASM_SYMBOL_EXPORTED; 1491 if (WS.getName() != WS.getImportName()) 1492 Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME; 1493 1494 wasm::WasmSymbolInfo Info; 1495 Info.Name = WS.getName(); 1496 Info.Kind = WS.getType(); 1497 Info.Flags = Flags; 1498 if (!WS.isData()) { 1499 assert(WasmIndices.count(&WS) > 0); 1500 Info.ElementIndex = WasmIndices.find(&WS)->second; 1501 } else if (WS.isDefined()) { 1502 assert(DataLocations.count(&WS) > 0); 1503 Info.DataRef = DataLocations.find(&WS)->second; 1504 } 1505 WS.setIndex(SymbolInfos.size()); 1506 SymbolInfos.emplace_back(Info); 1507 } 1508 1509 { 1510 auto HandleReloc = [&](const WasmRelocationEntry &Rel) { 1511 // Functions referenced by a relocation need to put in the table. This is 1512 // purely to make the object file's provisional values readable, and is 1513 // ignored by the linker, which re-calculates the relocations itself. 1514 if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 && 1515 Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB) 1516 return; 1517 assert(Rel.Symbol->isFunction()); 1518 const MCSymbolWasm &WS = *resolveSymbol(*Rel.Symbol); 1519 uint32_t FunctionIndex = WasmIndices.find(&WS)->second; 1520 uint32_t TableIndex = TableElems.size() + InitialTableOffset; 1521 if (TableIndices.try_emplace(&WS, TableIndex).second) { 1522 LLVM_DEBUG(dbgs() << " -> adding " << WS.getName() 1523 << " to table: " << TableIndex << "\n"); 1524 TableElems.push_back(FunctionIndex); 1525 registerFunctionType(WS); 1526 } 1527 }; 1528 1529 for (const WasmRelocationEntry &RelEntry : CodeRelocations) 1530 HandleReloc(RelEntry); 1531 for (const WasmRelocationEntry &RelEntry : DataRelocations) 1532 HandleReloc(RelEntry); 1533 } 1534 1535 // Translate .init_array section contents into start functions. 1536 for (const MCSection &S : Asm) { 1537 const auto &WS = static_cast<const MCSectionWasm &>(S); 1538 if (WS.getSectionName().startswith(".fini_array")) 1539 report_fatal_error(".fini_array sections are unsupported"); 1540 if (!WS.getSectionName().startswith(".init_array")) 1541 continue; 1542 if (WS.getFragmentList().empty()) 1543 continue; 1544 1545 // init_array is expected to contain a single non-empty data fragment 1546 if (WS.getFragmentList().size() != 3) 1547 report_fatal_error("only one .init_array section fragment supported"); 1548 1549 auto IT = WS.begin(); 1550 const MCFragment &EmptyFrag = *IT; 1551 if (EmptyFrag.getKind() != MCFragment::FT_Data) 1552 report_fatal_error(".init_array section should be aligned"); 1553 1554 IT = std::next(IT); 1555 const MCFragment &AlignFrag = *IT; 1556 if (AlignFrag.getKind() != MCFragment::FT_Align) 1557 report_fatal_error(".init_array section should be aligned"); 1558 if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4)) 1559 report_fatal_error(".init_array section should be aligned for pointers"); 1560 1561 const MCFragment &Frag = *std::next(IT); 1562 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data) 1563 report_fatal_error("only data supported in .init_array section"); 1564 1565 uint16_t Priority = UINT16_MAX; 1566 unsigned PrefixLength = strlen(".init_array"); 1567 if (WS.getSectionName().size() > PrefixLength) { 1568 if (WS.getSectionName()[PrefixLength] != '.') 1569 report_fatal_error( 1570 ".init_array section priority should start with '.'"); 1571 if (WS.getSectionName() 1572 .substr(PrefixLength + 1) 1573 .getAsInteger(10, Priority)) 1574 report_fatal_error("invalid .init_array section priority"); 1575 } 1576 const auto &DataFrag = cast<MCDataFragment>(Frag); 1577 const SmallVectorImpl<char> &Contents = DataFrag.getContents(); 1578 for (const uint8_t * 1579 P = (const uint8_t *)Contents.data(), 1580 *End = (const uint8_t *)Contents.data() + Contents.size(); 1581 P != End; ++P) { 1582 if (*P != 0) 1583 report_fatal_error("non-symbolic data in .init_array section"); 1584 } 1585 for (const MCFixup &Fixup : DataFrag.getFixups()) { 1586 assert(Fixup.getKind() == 1587 MCFixup::getKindForSize(is64Bit() ? 8 : 4, false)); 1588 const MCExpr *Expr = Fixup.getValue(); 1589 auto *SymRef = dyn_cast<MCSymbolRefExpr>(Expr); 1590 if (!SymRef) 1591 report_fatal_error("fixups in .init_array should be symbol references"); 1592 const auto &TargetSym = cast<const MCSymbolWasm>(SymRef->getSymbol()); 1593 if (TargetSym.getIndex() == InvalidIndex) 1594 report_fatal_error("symbols in .init_array should exist in symbtab"); 1595 if (!TargetSym.isFunction()) 1596 report_fatal_error("symbols in .init_array should be for functions"); 1597 InitFuncs.push_back( 1598 std::make_pair(Priority, TargetSym.getIndex())); 1599 } 1600 } 1601 1602 // Write out the Wasm header. 1603 writeHeader(Asm); 1604 1605 writeTypeSection(Signatures); 1606 writeImportSection(Imports, DataSize, TableElems.size()); 1607 writeFunctionSection(Functions); 1608 // Skip the "table" section; we import the table instead. 1609 // Skip the "memory" section; we import the memory instead. 1610 writeEventSection(Events); 1611 writeExportSection(Exports); 1612 writeElemSection(TableElems); 1613 writeDataCountSection(); 1614 writeCodeSection(Asm, Layout, Functions); 1615 writeDataSection(); 1616 for (auto &CustomSection : CustomSections) 1617 writeCustomSection(CustomSection, Asm, Layout); 1618 writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats); 1619 writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations); 1620 writeRelocSection(DataSectionIndex, "DATA", DataRelocations); 1621 writeCustomRelocSections(); 1622 if (ProducersSection) 1623 writeCustomSection(*ProducersSection, Asm, Layout); 1624 if (TargetFeaturesSection) 1625 writeCustomSection(*TargetFeaturesSection, Asm, Layout); 1626 1627 // TODO: Translate the .comment section to the output. 1628 return W.OS.tell() - StartOffset; 1629 } 1630 1631 std::unique_ptr<MCObjectWriter> 1632 llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW, 1633 raw_pwrite_stream &OS) { 1634 return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS); 1635 } 1636