1 //===- lib/MC/WasmObjectWriter.cpp - Wasm File Writer ---------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements Wasm object file writer information. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/ADT/STLExtras.h" 15 #include "llvm/ADT/SmallPtrSet.h" 16 #include "llvm/BinaryFormat/Wasm.h" 17 #include "llvm/MC/MCAsmBackend.h" 18 #include "llvm/MC/MCAsmInfo.h" 19 #include "llvm/MC/MCAsmLayout.h" 20 #include "llvm/MC/MCAssembler.h" 21 #include "llvm/MC/MCContext.h" 22 #include "llvm/MC/MCExpr.h" 23 #include "llvm/MC/MCFixupKindInfo.h" 24 #include "llvm/MC/MCObjectFileInfo.h" 25 #include "llvm/MC/MCObjectWriter.h" 26 #include "llvm/MC/MCSectionWasm.h" 27 #include "llvm/MC/MCSymbolWasm.h" 28 #include "llvm/MC/MCValue.h" 29 #include "llvm/MC/MCWasmObjectWriter.h" 30 #include "llvm/Support/Casting.h" 31 #include "llvm/Support/Debug.h" 32 #include "llvm/Support/ErrorHandling.h" 33 #include "llvm/Support/LEB128.h" 34 #include "llvm/Support/StringSaver.h" 35 #include <vector> 36 37 using namespace llvm; 38 39 #define DEBUG_TYPE "mc" 40 41 namespace { 42 43 // For patching purposes, we need to remember where each section starts, both 44 // for patching up the section size field, and for patching up references to 45 // locations within the section. 46 struct SectionBookkeeping { 47 // Where the size of the section is written. 48 uint64_t SizeOffset; 49 // Where the contents of the section starts (after the header). 50 uint64_t ContentsOffset; 51 }; 52 53 // The signature of a wasm function, in a struct capable of being used as a 54 // DenseMap key. 55 struct WasmFunctionType { 56 // Support empty and tombstone instances, needed by DenseMap. 57 enum { Plain, Empty, Tombstone } State; 58 59 // The return types of the function. 60 SmallVector<wasm::ValType, 1> Returns; 61 62 // The parameter types of the function. 63 SmallVector<wasm::ValType, 4> Params; 64 65 WasmFunctionType() : State(Plain) {} 66 67 bool operator==(const WasmFunctionType &Other) const { 68 return State == Other.State && Returns == Other.Returns && 69 Params == Other.Params; 70 } 71 }; 72 73 // Traits for using WasmFunctionType in a DenseMap. 74 struct WasmFunctionTypeDenseMapInfo { 75 static WasmFunctionType getEmptyKey() { 76 WasmFunctionType FuncTy; 77 FuncTy.State = WasmFunctionType::Empty; 78 return FuncTy; 79 } 80 static WasmFunctionType getTombstoneKey() { 81 WasmFunctionType FuncTy; 82 FuncTy.State = WasmFunctionType::Tombstone; 83 return FuncTy; 84 } 85 static unsigned getHashValue(const WasmFunctionType &FuncTy) { 86 uintptr_t Value = FuncTy.State; 87 for (wasm::ValType Ret : FuncTy.Returns) 88 Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Ret)); 89 for (wasm::ValType Param : FuncTy.Params) 90 Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Param)); 91 return Value; 92 } 93 static bool isEqual(const WasmFunctionType &LHS, 94 const WasmFunctionType &RHS) { 95 return LHS == RHS; 96 } 97 }; 98 99 // A wasm data segment. A wasm binary contains only a single data section 100 // but that can contain many segments, each with their own virtual location 101 // in memory. Each MCSection data created by llvm is modeled as its own 102 // wasm data segment. 103 struct WasmDataSegment { 104 MCSectionWasm *Section; 105 StringRef Name; 106 uint32_t Offset; 107 SmallVector<char, 4> Data; 108 }; 109 110 // A wasm import to be written into the import section. 111 struct WasmImport { 112 StringRef ModuleName; 113 StringRef FieldName; 114 unsigned Kind; 115 int32_t Type; 116 }; 117 118 // A wasm function to be written into the function section. 119 struct WasmFunction { 120 int32_t Type; 121 const MCSymbolWasm *Sym; 122 }; 123 124 // A wasm export to be written into the export section. 125 struct WasmExport { 126 StringRef FieldName; 127 unsigned Kind; 128 uint32_t Index; 129 }; 130 131 // A wasm global to be written into the global section. 132 struct WasmGlobal { 133 wasm::ValType Type; 134 bool IsMutable; 135 bool HasImport; 136 uint64_t InitialValue; 137 uint32_t ImportIndex; 138 }; 139 140 // Information about a single relocation. 141 struct WasmRelocationEntry { 142 uint64_t Offset; // Where is the relocation. 143 const MCSymbolWasm *Symbol; // The symbol to relocate with. 144 int64_t Addend; // A value to add to the symbol. 145 unsigned Type; // The type of the relocation. 146 const MCSectionWasm *FixupSection;// The section the relocation is targeting. 147 148 WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol, 149 int64_t Addend, unsigned Type, 150 const MCSectionWasm *FixupSection) 151 : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type), 152 FixupSection(FixupSection) {} 153 154 bool hasAddend() const { 155 switch (Type) { 156 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB: 157 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: 158 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32: 159 return true; 160 default: 161 return false; 162 } 163 } 164 165 void print(raw_ostream &Out) const { 166 Out << "Off=" << Offset << ", Sym=" << *Symbol << ", Addend=" << Addend 167 << ", Type=" << Type 168 << ", FixupSection=" << FixupSection->getSectionName(); 169 } 170 171 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 172 LLVM_DUMP_METHOD void dump() const { print(dbgs()); } 173 #endif 174 }; 175 176 #if !defined(NDEBUG) 177 raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) { 178 Rel.print(OS); 179 return OS; 180 } 181 #endif 182 183 class WasmObjectWriter : public MCObjectWriter { 184 /// Helper struct for containing some precomputed information on symbols. 185 struct WasmSymbolData { 186 const MCSymbolWasm *Symbol; 187 StringRef Name; 188 189 // Support lexicographic sorting. 190 bool operator<(const WasmSymbolData &RHS) const { return Name < RHS.Name; } 191 }; 192 193 /// The target specific Wasm writer instance. 194 std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter; 195 196 // Relocations for fixing up references in the code section. 197 std::vector<WasmRelocationEntry> CodeRelocations; 198 199 // Relocations for fixing up references in the data section. 200 std::vector<WasmRelocationEntry> DataRelocations; 201 202 // Index values to use for fixing up call_indirect type indices. 203 // Maps function symbols to the index of the type of the function 204 DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices; 205 // Maps function symbols to the table element index space. Used 206 // for TABLE_INDEX relocation types (i.e. address taken functions). 207 DenseMap<const MCSymbolWasm *, uint32_t> IndirectSymbolIndices; 208 // Maps function/global symbols to the function/global index space. 209 DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices; 210 211 DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo> 212 FunctionTypeIndices; 213 SmallVector<WasmFunctionType, 4> FunctionTypes; 214 SmallVector<WasmGlobal, 4> Globals; 215 unsigned NumGlobalImports = 0; 216 217 // TargetObjectWriter wrappers. 218 bool is64Bit() const { return TargetObjectWriter->is64Bit(); } 219 unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const { 220 return TargetObjectWriter->getRelocType(Target, Fixup); 221 } 222 223 void startSection(SectionBookkeeping &Section, unsigned SectionId, 224 const char *Name = nullptr); 225 void endSection(SectionBookkeeping &Section); 226 227 public: 228 WasmObjectWriter(MCWasmObjectTargetWriter *MOTW, raw_pwrite_stream &OS) 229 : MCObjectWriter(OS, /*IsLittleEndian=*/true), TargetObjectWriter(MOTW) {} 230 231 private: 232 ~WasmObjectWriter() override; 233 234 void reset() override { 235 CodeRelocations.clear(); 236 DataRelocations.clear(); 237 TypeIndices.clear(); 238 SymbolIndices.clear(); 239 IndirectSymbolIndices.clear(); 240 FunctionTypeIndices.clear(); 241 FunctionTypes.clear(); 242 Globals.clear(); 243 MCObjectWriter::reset(); 244 NumGlobalImports = 0; 245 } 246 247 void writeHeader(const MCAssembler &Asm); 248 249 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout, 250 const MCFragment *Fragment, const MCFixup &Fixup, 251 MCValue Target, uint64_t &FixedValue) override; 252 253 void executePostLayoutBinding(MCAssembler &Asm, 254 const MCAsmLayout &Layout) override; 255 256 void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override; 257 258 void writeString(const StringRef Str) { 259 encodeULEB128(Str.size(), getStream()); 260 writeBytes(Str); 261 } 262 263 void writeValueType(wasm::ValType Ty) { 264 encodeSLEB128(int32_t(Ty), getStream()); 265 } 266 267 void writeTypeSection(ArrayRef<WasmFunctionType> FunctionTypes); 268 void writeImportSection(ArrayRef<WasmImport> Imports); 269 void writeFunctionSection(ArrayRef<WasmFunction> Functions); 270 void writeTableSection(uint32_t NumElements); 271 void writeMemorySection(uint32_t DataSize); 272 void writeGlobalSection(); 273 void writeExportSection(ArrayRef<WasmExport> Exports); 274 void writeElemSection(ArrayRef<uint32_t> TableElems); 275 void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout, 276 ArrayRef<WasmFunction> Functions); 277 void writeDataSection(ArrayRef<WasmDataSegment> Segments); 278 void writeNameSection(ArrayRef<WasmFunction> Functions, 279 ArrayRef<WasmImport> Imports, 280 uint32_t NumFuncImports); 281 void writeCodeRelocSection(); 282 void writeDataRelocSection(); 283 void writeLinkingMetaDataSection( 284 ArrayRef<WasmDataSegment> Segments, uint32_t DataSize, 285 uint32_t DataAlignment, 286 SmallVector<std::pair<StringRef, uint32_t>, 4> SymbolFlags, 287 bool HasStackPointer, uint32_t StackPointerGlobal); 288 289 uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry); 290 void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations, 291 uint64_t ContentsOffset); 292 293 void writeRelocations(ArrayRef<WasmRelocationEntry> Relocations); 294 uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry); 295 uint32_t getFunctionType(const MCSymbolWasm& Symbol); 296 uint32_t registerFunctionType(const MCSymbolWasm& Symbol); 297 }; 298 299 } // end anonymous namespace 300 301 WasmObjectWriter::~WasmObjectWriter() {} 302 303 // Write out a section header and a patchable section size field. 304 void WasmObjectWriter::startSection(SectionBookkeeping &Section, 305 unsigned SectionId, 306 const char *Name) { 307 assert((Name != nullptr) == (SectionId == wasm::WASM_SEC_CUSTOM) && 308 "Only custom sections can have names"); 309 310 DEBUG(dbgs() << "startSection " << SectionId << ": " << Name << "\n"); 311 encodeULEB128(SectionId, getStream()); 312 313 Section.SizeOffset = getStream().tell(); 314 315 // The section size. We don't know the size yet, so reserve enough space 316 // for any 32-bit value; we'll patch it later. 317 encodeULEB128(UINT32_MAX, getStream()); 318 319 // The position where the section starts, for measuring its size. 320 Section.ContentsOffset = getStream().tell(); 321 322 // Custom sections in wasm also have a string identifier. 323 if (SectionId == wasm::WASM_SEC_CUSTOM) { 324 assert(Name); 325 writeString(StringRef(Name)); 326 } 327 } 328 329 // Now that the section is complete and we know how big it is, patch up the 330 // section size field at the start of the section. 331 void WasmObjectWriter::endSection(SectionBookkeeping &Section) { 332 uint64_t Size = getStream().tell() - Section.ContentsOffset; 333 if (uint32_t(Size) != Size) 334 report_fatal_error("section size does not fit in a uint32_t"); 335 336 DEBUG(dbgs() << "endSection size=" << Size << "\n"); 337 338 // Write the final section size to the payload_len field, which follows 339 // the section id byte. 340 uint8_t Buffer[16]; 341 unsigned SizeLen = encodeULEB128(Size, Buffer, 5); 342 assert(SizeLen == 5); 343 getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset); 344 } 345 346 // Emit the Wasm header. 347 void WasmObjectWriter::writeHeader(const MCAssembler &Asm) { 348 writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic))); 349 writeLE32(wasm::WasmVersion); 350 } 351 352 void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm, 353 const MCAsmLayout &Layout) { 354 } 355 356 void WasmObjectWriter::recordRelocation(MCAssembler &Asm, 357 const MCAsmLayout &Layout, 358 const MCFragment *Fragment, 359 const MCFixup &Fixup, MCValue Target, 360 uint64_t &FixedValue) { 361 MCAsmBackend &Backend = Asm.getBackend(); 362 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags & 363 MCFixupKindInfo::FKF_IsPCRel; 364 const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent()); 365 uint64_t C = Target.getConstant(); 366 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset(); 367 MCContext &Ctx = Asm.getContext(); 368 369 if (const MCSymbolRefExpr *RefB = Target.getSymB()) { 370 assert(RefB->getKind() == MCSymbolRefExpr::VK_None && 371 "Should not have constructed this"); 372 373 // Let A, B and C being the components of Target and R be the location of 374 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C). 375 // If it is pcrel, we want to compute (A - B + C - R). 376 377 // In general, Wasm has no relocations for -B. It can only represent (A + C) 378 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can 379 // replace B to implement it: (A - R - K + C) 380 if (IsPCRel) { 381 Ctx.reportError( 382 Fixup.getLoc(), 383 "No relocation available to represent this relative expression"); 384 return; 385 } 386 387 const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol()); 388 389 if (SymB.isUndefined()) { 390 Ctx.reportError(Fixup.getLoc(), 391 Twine("symbol '") + SymB.getName() + 392 "' can not be undefined in a subtraction expression"); 393 return; 394 } 395 396 assert(!SymB.isAbsolute() && "Should have been folded"); 397 const MCSection &SecB = SymB.getSection(); 398 if (&SecB != &FixupSection) { 399 Ctx.reportError(Fixup.getLoc(), 400 "Cannot represent a difference across sections"); 401 return; 402 } 403 404 uint64_t SymBOffset = Layout.getSymbolOffset(SymB); 405 uint64_t K = SymBOffset - FixupOffset; 406 IsPCRel = true; 407 C -= K; 408 } 409 410 // We either rejected the fixup or folded B into C at this point. 411 const MCSymbolRefExpr *RefA = Target.getSymA(); 412 const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr; 413 414 if (SymA && SymA->isVariable()) { 415 const MCExpr *Expr = SymA->getVariableValue(); 416 const auto *Inner = cast<MCSymbolRefExpr>(Expr); 417 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF) 418 llvm_unreachable("weakref used in reloc not yet implemented"); 419 } 420 421 // Put any constant offset in an addend. Offsets can be negative, and 422 // LLVM expects wrapping, in contrast to wasm's immediates which can't 423 // be negative and don't wrap. 424 FixedValue = 0; 425 426 if (SymA) 427 SymA->setUsedInReloc(); 428 429 assert(!IsPCRel); 430 assert(SymA); 431 432 unsigned Type = getRelocType(Target, Fixup); 433 434 WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection); 435 DEBUG(dbgs() << "WasmReloc: " << Rec << "\n"); 436 437 if (FixupSection.hasInstructions()) 438 CodeRelocations.push_back(Rec); 439 else 440 DataRelocations.push_back(Rec); 441 } 442 443 // Write X as an (unsigned) LEB value at offset Offset in Stream, padded 444 // to allow patching. 445 static void 446 WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) { 447 uint8_t Buffer[5]; 448 unsigned SizeLen = encodeULEB128(X, Buffer, 5); 449 assert(SizeLen == 5); 450 Stream.pwrite((char *)Buffer, SizeLen, Offset); 451 } 452 453 // Write X as an signed LEB value at offset Offset in Stream, padded 454 // to allow patching. 455 static void 456 WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) { 457 uint8_t Buffer[5]; 458 unsigned SizeLen = encodeSLEB128(X, Buffer, 5); 459 assert(SizeLen == 5); 460 Stream.pwrite((char *)Buffer, SizeLen, Offset); 461 } 462 463 // Write X as a plain integer value at offset Offset in Stream. 464 static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) { 465 uint8_t Buffer[4]; 466 support::endian::write32le(Buffer, X); 467 Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset); 468 } 469 470 static const MCSymbolWasm* ResolveSymbol(const MCSymbolWasm& Symbol) { 471 if (Symbol.isVariable()) { 472 const MCExpr *Expr = Symbol.getVariableValue(); 473 auto *Inner = cast<MCSymbolRefExpr>(Expr); 474 return cast<MCSymbolWasm>(&Inner->getSymbol()); 475 } 476 return &Symbol; 477 } 478 479 // Compute a value to write into the code at the location covered 480 // by RelEntry. This value isn't used by the static linker, since 481 // we have addends; it just serves to make the code more readable 482 // and to make standalone wasm modules directly usable. 483 uint32_t 484 WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) { 485 const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol); 486 487 // For undefined symbols, use a hopefully invalid value. 488 if (!Sym->isDefined(/*SetUsed=*/false)) 489 return UINT32_MAX; 490 491 uint32_t GlobalIndex = SymbolIndices[Sym]; 492 const WasmGlobal& Global = Globals[GlobalIndex - NumGlobalImports]; 493 uint64_t Address = Global.InitialValue + RelEntry.Addend; 494 495 // Ignore overflow. LLVM allows address arithmetic to silently wrap. 496 uint32_t Value = Address; 497 498 return Value; 499 } 500 501 static void addData(SmallVectorImpl<char> &DataBytes, 502 MCSectionWasm &DataSection, uint32_t &DataAlignment) { 503 DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment())); 504 DataAlignment = std::max(DataAlignment, DataSection.getAlignment()); 505 DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n"); 506 507 for (const MCFragment &Frag : DataSection) { 508 if (Frag.hasInstructions()) 509 report_fatal_error("only data supported in data sections"); 510 511 if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) { 512 if (Align->getValueSize() != 1) 513 report_fatal_error("only byte values supported for alignment"); 514 // If nops are requested, use zeros, as this is the data section. 515 uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue(); 516 uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(), 517 Align->getAlignment()), 518 DataBytes.size() + 519 Align->getMaxBytesToEmit()); 520 DataBytes.resize(Size, Value); 521 } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) { 522 DataBytes.insert(DataBytes.end(), Fill->getSize(), Fill->getValue()); 523 } else { 524 const auto &DataFrag = cast<MCDataFragment>(Frag); 525 const SmallVectorImpl<char> &Contents = DataFrag.getContents(); 526 527 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end()); 528 } 529 } 530 531 DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n"); 532 } 533 534 uint32_t WasmObjectWriter::getRelocationIndexValue( 535 const WasmRelocationEntry &RelEntry) { 536 switch (RelEntry.Type) { 537 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB: 538 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: 539 if (!IndirectSymbolIndices.count(RelEntry.Symbol)) 540 report_fatal_error("symbol not found table index space: " + 541 RelEntry.Symbol->getName()); 542 return IndirectSymbolIndices[RelEntry.Symbol]; 543 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB: 544 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB: 545 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB: 546 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: 547 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32: 548 if (!SymbolIndices.count(RelEntry.Symbol)) 549 report_fatal_error("symbol not found function/global index space: " + 550 RelEntry.Symbol->getName()); 551 return SymbolIndices[RelEntry.Symbol]; 552 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB: 553 if (!TypeIndices.count(RelEntry.Symbol)) 554 report_fatal_error("symbol not found in type index space: " + 555 RelEntry.Symbol->getName()); 556 return TypeIndices[RelEntry.Symbol]; 557 default: 558 llvm_unreachable("invalid relocation type"); 559 } 560 } 561 562 // Apply the portions of the relocation records that we can handle ourselves 563 // directly. 564 void WasmObjectWriter::applyRelocations( 565 ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) { 566 raw_pwrite_stream &Stream = getStream(); 567 for (const WasmRelocationEntry &RelEntry : Relocations) { 568 uint64_t Offset = ContentsOffset + 569 RelEntry.FixupSection->getSectionOffset() + 570 RelEntry.Offset; 571 572 DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n"); 573 switch (RelEntry.Type) { 574 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB: 575 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB: 576 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB: 577 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB: { 578 uint32_t Index = getRelocationIndexValue(RelEntry); 579 WritePatchableSLEB(Stream, Index, Offset); 580 break; 581 } 582 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: { 583 uint32_t Index = getRelocationIndexValue(RelEntry); 584 WriteI32(Stream, Index, Offset); 585 break; 586 } 587 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: { 588 uint32_t Value = getProvisionalValue(RelEntry); 589 WritePatchableSLEB(Stream, Value, Offset); 590 break; 591 } 592 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB: { 593 uint32_t Value = getProvisionalValue(RelEntry); 594 WritePatchableLEB(Stream, Value, Offset); 595 break; 596 } 597 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32: { 598 uint32_t Value = getProvisionalValue(RelEntry); 599 WriteI32(Stream, Value, Offset); 600 break; 601 } 602 default: 603 llvm_unreachable("invalid relocation type"); 604 } 605 } 606 } 607 608 // Write out the portions of the relocation records that the linker will 609 // need to handle. 610 void WasmObjectWriter::writeRelocations( 611 ArrayRef<WasmRelocationEntry> Relocations) { 612 raw_pwrite_stream &Stream = getStream(); 613 for (const WasmRelocationEntry& RelEntry : Relocations) { 614 615 uint64_t Offset = RelEntry.Offset + 616 RelEntry.FixupSection->getSectionOffset(); 617 uint32_t Index = getRelocationIndexValue(RelEntry); 618 619 encodeULEB128(RelEntry.Type, Stream); 620 encodeULEB128(Offset, Stream); 621 encodeULEB128(Index, Stream); 622 if (RelEntry.hasAddend()) 623 encodeSLEB128(RelEntry.Addend, Stream); 624 } 625 } 626 627 void WasmObjectWriter::writeTypeSection( 628 ArrayRef<WasmFunctionType> FunctionTypes) { 629 if (FunctionTypes.empty()) 630 return; 631 632 SectionBookkeeping Section; 633 startSection(Section, wasm::WASM_SEC_TYPE); 634 635 encodeULEB128(FunctionTypes.size(), getStream()); 636 637 for (const WasmFunctionType &FuncTy : FunctionTypes) { 638 encodeSLEB128(wasm::WASM_TYPE_FUNC, getStream()); 639 encodeULEB128(FuncTy.Params.size(), getStream()); 640 for (wasm::ValType Ty : FuncTy.Params) 641 writeValueType(Ty); 642 encodeULEB128(FuncTy.Returns.size(), getStream()); 643 for (wasm::ValType Ty : FuncTy.Returns) 644 writeValueType(Ty); 645 } 646 647 endSection(Section); 648 } 649 650 void WasmObjectWriter::writeImportSection(ArrayRef<WasmImport> Imports) { 651 if (Imports.empty()) 652 return; 653 654 SectionBookkeeping Section; 655 startSection(Section, wasm::WASM_SEC_IMPORT); 656 657 encodeULEB128(Imports.size(), getStream()); 658 for (const WasmImport &Import : Imports) { 659 writeString(Import.ModuleName); 660 writeString(Import.FieldName); 661 662 encodeULEB128(Import.Kind, getStream()); 663 664 switch (Import.Kind) { 665 case wasm::WASM_EXTERNAL_FUNCTION: 666 encodeULEB128(Import.Type, getStream()); 667 break; 668 case wasm::WASM_EXTERNAL_GLOBAL: 669 encodeSLEB128(int32_t(Import.Type), getStream()); 670 encodeULEB128(0, getStream()); // mutability 671 break; 672 default: 673 llvm_unreachable("unsupported import kind"); 674 } 675 } 676 677 endSection(Section); 678 } 679 680 void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) { 681 if (Functions.empty()) 682 return; 683 684 SectionBookkeeping Section; 685 startSection(Section, wasm::WASM_SEC_FUNCTION); 686 687 encodeULEB128(Functions.size(), getStream()); 688 for (const WasmFunction &Func : Functions) 689 encodeULEB128(Func.Type, getStream()); 690 691 endSection(Section); 692 } 693 694 void WasmObjectWriter::writeTableSection(uint32_t NumElements) { 695 // For now, always emit the table section, since indirect calls are not 696 // valid without it. In the future, we could perhaps be more clever and omit 697 // it if there are no indirect calls. 698 699 SectionBookkeeping Section; 700 startSection(Section, wasm::WASM_SEC_TABLE); 701 702 encodeULEB128(1, getStream()); // The number of tables. 703 // Fixed to 1 for now. 704 encodeSLEB128(wasm::WASM_TYPE_ANYFUNC, getStream()); // Type of table 705 encodeULEB128(0, getStream()); // flags 706 encodeULEB128(NumElements, getStream()); // initial 707 708 endSection(Section); 709 } 710 711 void WasmObjectWriter::writeMemorySection(uint32_t DataSize) { 712 // For now, always emit the memory section, since loads and stores are not 713 // valid without it. In the future, we could perhaps be more clever and omit 714 // it if there are no loads or stores. 715 SectionBookkeeping Section; 716 uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize; 717 718 startSection(Section, wasm::WASM_SEC_MEMORY); 719 encodeULEB128(1, getStream()); // number of memory spaces 720 721 encodeULEB128(0, getStream()); // flags 722 encodeULEB128(NumPages, getStream()); // initial 723 724 endSection(Section); 725 } 726 727 void WasmObjectWriter::writeGlobalSection() { 728 if (Globals.empty()) 729 return; 730 731 SectionBookkeeping Section; 732 startSection(Section, wasm::WASM_SEC_GLOBAL); 733 734 encodeULEB128(Globals.size(), getStream()); 735 for (const WasmGlobal &Global : Globals) { 736 writeValueType(Global.Type); 737 write8(Global.IsMutable); 738 739 if (Global.HasImport) { 740 assert(Global.InitialValue == 0); 741 write8(wasm::WASM_OPCODE_GET_GLOBAL); 742 encodeULEB128(Global.ImportIndex, getStream()); 743 } else { 744 assert(Global.ImportIndex == 0); 745 write8(wasm::WASM_OPCODE_I32_CONST); 746 encodeSLEB128(Global.InitialValue, getStream()); // offset 747 } 748 write8(wasm::WASM_OPCODE_END); 749 } 750 751 endSection(Section); 752 } 753 754 void WasmObjectWriter::writeExportSection(ArrayRef<WasmExport> Exports) { 755 if (Exports.empty()) 756 return; 757 758 SectionBookkeeping Section; 759 startSection(Section, wasm::WASM_SEC_EXPORT); 760 761 encodeULEB128(Exports.size(), getStream()); 762 for (const WasmExport &Export : Exports) { 763 writeString(Export.FieldName); 764 encodeSLEB128(Export.Kind, getStream()); 765 encodeULEB128(Export.Index, getStream()); 766 } 767 768 endSection(Section); 769 } 770 771 void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) { 772 if (TableElems.empty()) 773 return; 774 775 SectionBookkeeping Section; 776 startSection(Section, wasm::WASM_SEC_ELEM); 777 778 encodeULEB128(1, getStream()); // number of "segments" 779 encodeULEB128(0, getStream()); // the table index 780 781 // init expr for starting offset 782 write8(wasm::WASM_OPCODE_I32_CONST); 783 encodeSLEB128(0, getStream()); 784 write8(wasm::WASM_OPCODE_END); 785 786 encodeULEB128(TableElems.size(), getStream()); 787 for (uint32_t Elem : TableElems) 788 encodeULEB128(Elem, getStream()); 789 790 endSection(Section); 791 } 792 793 void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm, 794 const MCAsmLayout &Layout, 795 ArrayRef<WasmFunction> Functions) { 796 if (Functions.empty()) 797 return; 798 799 SectionBookkeeping Section; 800 startSection(Section, wasm::WASM_SEC_CODE); 801 802 encodeULEB128(Functions.size(), getStream()); 803 804 for (const WasmFunction &Func : Functions) { 805 auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection()); 806 807 int64_t Size = 0; 808 if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout)) 809 report_fatal_error(".size expression must be evaluatable"); 810 811 encodeULEB128(Size, getStream()); 812 FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset); 813 Asm.writeSectionData(&FuncSection, Layout); 814 } 815 816 // Apply fixups. 817 applyRelocations(CodeRelocations, Section.ContentsOffset); 818 819 endSection(Section); 820 } 821 822 void WasmObjectWriter::writeDataSection(ArrayRef<WasmDataSegment> Segments) { 823 if (Segments.empty()) 824 return; 825 826 SectionBookkeeping Section; 827 startSection(Section, wasm::WASM_SEC_DATA); 828 829 encodeULEB128(Segments.size(), getStream()); // count 830 831 for (const WasmDataSegment & Segment : Segments) { 832 encodeULEB128(0, getStream()); // memory index 833 write8(wasm::WASM_OPCODE_I32_CONST); 834 encodeSLEB128(Segment.Offset, getStream()); // offset 835 write8(wasm::WASM_OPCODE_END); 836 encodeULEB128(Segment.Data.size(), getStream()); // size 837 Segment.Section->setSectionOffset(getStream().tell() - Section.ContentsOffset); 838 writeBytes(Segment.Data); // data 839 } 840 841 // Apply fixups. 842 applyRelocations(DataRelocations, Section.ContentsOffset); 843 844 endSection(Section); 845 } 846 847 void WasmObjectWriter::writeNameSection( 848 ArrayRef<WasmFunction> Functions, 849 ArrayRef<WasmImport> Imports, 850 unsigned NumFuncImports) { 851 uint32_t TotalFunctions = NumFuncImports + Functions.size(); 852 if (TotalFunctions == 0) 853 return; 854 855 SectionBookkeeping Section; 856 startSection(Section, wasm::WASM_SEC_CUSTOM, "name"); 857 SectionBookkeeping SubSection; 858 startSection(SubSection, wasm::WASM_NAMES_FUNCTION); 859 860 encodeULEB128(TotalFunctions, getStream()); 861 uint32_t Index = 0; 862 for (const WasmImport &Import : Imports) { 863 if (Import.Kind == wasm::WASM_EXTERNAL_FUNCTION) { 864 encodeULEB128(Index, getStream()); 865 writeString(Import.FieldName); 866 ++Index; 867 } 868 } 869 for (const WasmFunction &Func : Functions) { 870 encodeULEB128(Index, getStream()); 871 writeString(Func.Sym->getName()); 872 ++Index; 873 } 874 875 endSection(SubSection); 876 endSection(Section); 877 } 878 879 void WasmObjectWriter::writeCodeRelocSection() { 880 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md 881 // for descriptions of the reloc sections. 882 883 if (CodeRelocations.empty()) 884 return; 885 886 SectionBookkeeping Section; 887 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.CODE"); 888 889 encodeULEB128(wasm::WASM_SEC_CODE, getStream()); 890 encodeULEB128(CodeRelocations.size(), getStream()); 891 892 writeRelocations(CodeRelocations); 893 894 endSection(Section); 895 } 896 897 void WasmObjectWriter::writeDataRelocSection() { 898 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md 899 // for descriptions of the reloc sections. 900 901 if (DataRelocations.empty()) 902 return; 903 904 SectionBookkeeping Section; 905 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.DATA"); 906 907 encodeULEB128(wasm::WASM_SEC_DATA, getStream()); 908 encodeULEB128(DataRelocations.size(), getStream()); 909 910 writeRelocations(DataRelocations); 911 912 endSection(Section); 913 } 914 915 void WasmObjectWriter::writeLinkingMetaDataSection( 916 ArrayRef<WasmDataSegment> Segments, uint32_t DataSize, 917 uint32_t DataAlignment, 918 SmallVector<std::pair<StringRef, uint32_t>, 4> SymbolFlags, 919 bool HasStackPointer, uint32_t StackPointerGlobal) { 920 SectionBookkeeping Section; 921 startSection(Section, wasm::WASM_SEC_CUSTOM, "linking"); 922 SectionBookkeeping SubSection; 923 924 if (HasStackPointer) { 925 startSection(SubSection, wasm::WASM_STACK_POINTER); 926 encodeULEB128(StackPointerGlobal, getStream()); // id 927 endSection(SubSection); 928 } 929 930 if (SymbolFlags.size() != 0) { 931 startSection(SubSection, wasm::WASM_SYMBOL_INFO); 932 encodeULEB128(SymbolFlags.size(), getStream()); 933 for (auto Pair: SymbolFlags) { 934 writeString(Pair.first); 935 encodeULEB128(Pair.second, getStream()); 936 } 937 endSection(SubSection); 938 } 939 940 if (DataSize > 0) { 941 startSection(SubSection, wasm::WASM_DATA_SIZE); 942 encodeULEB128(DataSize, getStream()); 943 endSection(SubSection); 944 945 startSection(SubSection, wasm::WASM_DATA_ALIGNMENT); 946 encodeULEB128(DataAlignment, getStream()); 947 endSection(SubSection); 948 } 949 950 if (Segments.size()) { 951 startSection(SubSection, wasm::WASM_SEGMENT_NAMES); 952 encodeULEB128(Segments.size(), getStream()); 953 for (const WasmDataSegment &Segment : Segments) 954 writeString(Segment.Name); 955 endSection(SubSection); 956 } 957 958 endSection(Section); 959 } 960 961 uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm& Symbol) { 962 assert(Symbol.isFunction()); 963 assert(TypeIndices.count(&Symbol)); 964 return TypeIndices[&Symbol]; 965 } 966 967 uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm& Symbol) { 968 assert(Symbol.isFunction()); 969 970 WasmFunctionType F; 971 const MCSymbolWasm* ResolvedSym = ResolveSymbol(Symbol); 972 F.Returns = ResolvedSym->getReturns(); 973 F.Params = ResolvedSym->getParams(); 974 975 auto Pair = 976 FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size())); 977 if (Pair.second) 978 FunctionTypes.push_back(F); 979 TypeIndices[&Symbol] = Pair.first->second; 980 981 DEBUG(dbgs() << "registerFunctionType: " << Symbol << " new:" << Pair.second << "\n"); 982 DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n"); 983 return Pair.first->second; 984 } 985 986 void WasmObjectWriter::writeObject(MCAssembler &Asm, 987 const MCAsmLayout &Layout) { 988 DEBUG(dbgs() << "WasmObjectWriter::writeObject\n"); 989 MCContext &Ctx = Asm.getContext(); 990 wasm::ValType PtrType = is64Bit() ? wasm::ValType::I64 : wasm::ValType::I32; 991 992 // Collect information from the available symbols. 993 SmallVector<WasmFunction, 4> Functions; 994 SmallVector<uint32_t, 4> TableElems; 995 SmallVector<WasmImport, 4> Imports; 996 SmallVector<WasmExport, 4> Exports; 997 SmallVector<std::pair<StringRef, uint32_t>, 4> SymbolFlags; 998 SmallPtrSet<const MCSymbolWasm *, 4> IsAddressTaken; 999 unsigned NumFuncImports = 0; 1000 SmallVector<WasmDataSegment, 4> DataSegments; 1001 uint32_t DataAlignment = 1; 1002 uint32_t StackPointerGlobal = 0; 1003 uint32_t DataSize = 0; 1004 bool HasStackPointer = false; 1005 1006 // Populate the IsAddressTaken set. 1007 for (const WasmRelocationEntry &RelEntry : CodeRelocations) { 1008 switch (RelEntry.Type) { 1009 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB: 1010 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: 1011 IsAddressTaken.insert(RelEntry.Symbol); 1012 break; 1013 default: 1014 break; 1015 } 1016 } 1017 for (const WasmRelocationEntry &RelEntry : DataRelocations) { 1018 switch (RelEntry.Type) { 1019 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: 1020 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32: 1021 IsAddressTaken.insert(RelEntry.Symbol); 1022 break; 1023 default: 1024 break; 1025 } 1026 } 1027 1028 // Populate FunctionTypeIndices and Imports. 1029 for (const MCSymbol &S : Asm.symbols()) { 1030 const auto &WS = static_cast<const MCSymbolWasm &>(S); 1031 1032 if (WS.isTemporary()) 1033 continue; 1034 1035 if (WS.isFunction()) 1036 registerFunctionType(WS); 1037 1038 // If the symbol is not defined in this translation unit, import it. 1039 if (!WS.isDefined(/*SetUsed=*/false)) { 1040 WasmImport Import; 1041 Import.ModuleName = WS.getModuleName(); 1042 Import.FieldName = WS.getName(); 1043 1044 if (WS.isFunction()) { 1045 Import.Kind = wasm::WASM_EXTERNAL_FUNCTION; 1046 Import.Type = getFunctionType(WS); 1047 SymbolIndices[&WS] = NumFuncImports; 1048 ++NumFuncImports; 1049 } else { 1050 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL; 1051 Import.Type = int32_t(PtrType); 1052 SymbolIndices[&WS] = NumGlobalImports; 1053 ++NumGlobalImports; 1054 } 1055 1056 Imports.push_back(Import); 1057 } 1058 } 1059 1060 // In the special .global_variables section, we've encoded global 1061 // variables used by the function. Translate them into the Globals 1062 // list. 1063 MCSectionWasm *GlobalVars = Ctx.getWasmSection(".global_variables", wasm::WASM_SEC_DATA); 1064 if (!GlobalVars->getFragmentList().empty()) { 1065 if (GlobalVars->getFragmentList().size() != 1) 1066 report_fatal_error("only one .global_variables fragment supported"); 1067 const MCFragment &Frag = *GlobalVars->begin(); 1068 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data) 1069 report_fatal_error("only data supported in .global_variables"); 1070 const auto &DataFrag = cast<MCDataFragment>(Frag); 1071 if (!DataFrag.getFixups().empty()) 1072 report_fatal_error("fixups not supported in .global_variables"); 1073 const SmallVectorImpl<char> &Contents = DataFrag.getContents(); 1074 for (const uint8_t *p = (const uint8_t *)Contents.data(), 1075 *end = (const uint8_t *)Contents.data() + Contents.size(); 1076 p != end; ) { 1077 WasmGlobal G; 1078 if (end - p < 3) 1079 report_fatal_error("truncated global variable encoding"); 1080 G.Type = wasm::ValType(int8_t(*p++)); 1081 G.IsMutable = bool(*p++); 1082 G.HasImport = bool(*p++); 1083 if (G.HasImport) { 1084 G.InitialValue = 0; 1085 1086 WasmImport Import; 1087 Import.ModuleName = (const char *)p; 1088 const uint8_t *nul = (const uint8_t *)memchr(p, '\0', end - p); 1089 if (!nul) 1090 report_fatal_error("global module name must be nul-terminated"); 1091 p = nul + 1; 1092 nul = (const uint8_t *)memchr(p, '\0', end - p); 1093 if (!nul) 1094 report_fatal_error("global base name must be nul-terminated"); 1095 Import.FieldName = (const char *)p; 1096 p = nul + 1; 1097 1098 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL; 1099 Import.Type = int32_t(G.Type); 1100 1101 G.ImportIndex = NumGlobalImports; 1102 ++NumGlobalImports; 1103 1104 Imports.push_back(Import); 1105 } else { 1106 unsigned n; 1107 G.InitialValue = decodeSLEB128(p, &n); 1108 G.ImportIndex = 0; 1109 if ((ptrdiff_t)n > end - p) 1110 report_fatal_error("global initial value must be valid SLEB128"); 1111 p += n; 1112 } 1113 Globals.push_back(G); 1114 } 1115 } 1116 1117 // In the special .stack_pointer section, we've encoded the stack pointer 1118 // index. 1119 MCSectionWasm *StackPtr = Ctx.getWasmSection(".stack_pointer", wasm::WASM_SEC_DATA); 1120 if (!StackPtr->getFragmentList().empty()) { 1121 if (StackPtr->getFragmentList().size() != 1) 1122 report_fatal_error("only one .stack_pointer fragment supported"); 1123 const MCFragment &Frag = *StackPtr->begin(); 1124 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data) 1125 report_fatal_error("only data supported in .stack_pointer"); 1126 const auto &DataFrag = cast<MCDataFragment>(Frag); 1127 if (!DataFrag.getFixups().empty()) 1128 report_fatal_error("fixups not supported in .stack_pointer"); 1129 const SmallVectorImpl<char> &Contents = DataFrag.getContents(); 1130 if (Contents.size() != 4) 1131 report_fatal_error("only one entry supported in .stack_pointer"); 1132 HasStackPointer = true; 1133 StackPointerGlobal = NumGlobalImports + *(const int32_t *)Contents.data(); 1134 } 1135 1136 for (MCSection &Sec : Asm) { 1137 auto &Section = static_cast<MCSectionWasm &>(Sec); 1138 if (Section.getType() != wasm::WASM_SEC_DATA) 1139 continue; 1140 1141 DataSize = alignTo(DataSize, Section.getAlignment()); 1142 DataSegments.emplace_back(); 1143 WasmDataSegment &Segment = DataSegments.back(); 1144 Segment.Name = Section.getSectionName(); 1145 Segment.Offset = DataSize; 1146 Segment.Section = &Section; 1147 addData(Segment.Data, Section, DataAlignment); 1148 DataSize += Segment.Data.size(); 1149 Section.setMemoryOffset(Segment.Offset); 1150 } 1151 1152 // Handle regular defined and undefined symbols. 1153 for (const MCSymbol &S : Asm.symbols()) { 1154 // Ignore unnamed temporary symbols, which aren't ever exported, imported, 1155 // or used in relocations. 1156 if (S.isTemporary() && S.getName().empty()) 1157 continue; 1158 1159 const auto &WS = static_cast<const MCSymbolWasm &>(S); 1160 DEBUG(dbgs() << "MCSymbol: '" << S << "'" 1161 << " isDefined=" << S.isDefined() << " isExternal=" 1162 << S.isExternal() << " isTemporary=" << S.isTemporary() 1163 << " isFunction=" << WS.isFunction() 1164 << " isWeak=" << WS.isWeak() 1165 << " isVariable=" << WS.isVariable() << "\n"); 1166 1167 if (WS.isWeak()) 1168 SymbolFlags.emplace_back(WS.getName(), wasm::WASM_SYMBOL_BINDING_WEAK); 1169 1170 if (WS.isVariable()) 1171 continue; 1172 1173 unsigned Index; 1174 1175 if (WS.isFunction()) { 1176 if (WS.isDefined(/*SetUsed=*/false)) { 1177 if (WS.getOffset() != 0) 1178 report_fatal_error( 1179 "function sections must contain one function each"); 1180 1181 if (WS.getSize() == 0) 1182 report_fatal_error( 1183 "function symbols must have a size set with .size"); 1184 1185 // A definition. Take the next available index. 1186 Index = NumFuncImports + Functions.size(); 1187 1188 // Prepare the function. 1189 WasmFunction Func; 1190 Func.Type = getFunctionType(WS); 1191 Func.Sym = &WS; 1192 SymbolIndices[&WS] = Index; 1193 Functions.push_back(Func); 1194 } else { 1195 // An import; the index was assigned above. 1196 Index = SymbolIndices.find(&WS)->second; 1197 } 1198 1199 DEBUG(dbgs() << " -> function index: " << Index << "\n"); 1200 1201 // If needed, prepare the function to be called indirectly. 1202 if (IsAddressTaken.count(&WS) != 0) { 1203 IndirectSymbolIndices[&WS] = TableElems.size(); 1204 DEBUG(dbgs() << " -> adding to table: " << TableElems.size() << "\n"); 1205 TableElems.push_back(Index); 1206 } 1207 } else { 1208 if (WS.isTemporary() && !WS.getSize()) 1209 continue; 1210 1211 if (!WS.isDefined(/*SetUsed=*/false)) 1212 continue; 1213 1214 if (!WS.getSize()) 1215 report_fatal_error("data symbols must have a size set with .size: " + 1216 WS.getName()); 1217 1218 int64_t Size = 0; 1219 if (!WS.getSize()->evaluateAsAbsolute(Size, Layout)) 1220 report_fatal_error(".size expression must be evaluatable"); 1221 1222 // For each global, prepare a corresponding wasm global holding its 1223 // address. For externals these will also be named exports. 1224 Index = NumGlobalImports + Globals.size(); 1225 auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection()); 1226 1227 WasmGlobal Global; 1228 Global.Type = PtrType; 1229 Global.IsMutable = false; 1230 Global.HasImport = false; 1231 Global.InitialValue = DataSection.getMemoryOffset() + Layout.getSymbolOffset(WS); 1232 Global.ImportIndex = 0; 1233 SymbolIndices[&WS] = Index; 1234 DEBUG(dbgs() << " -> global index: " << Index << "\n"); 1235 Globals.push_back(Global); 1236 } 1237 1238 // If the symbol is visible outside this translation unit, export it. 1239 if (WS.isDefined(/*SetUsed=*/false)) { 1240 WasmExport Export; 1241 Export.FieldName = WS.getName(); 1242 Export.Index = Index; 1243 if (WS.isFunction()) 1244 Export.Kind = wasm::WASM_EXTERNAL_FUNCTION; 1245 else 1246 Export.Kind = wasm::WASM_EXTERNAL_GLOBAL; 1247 DEBUG(dbgs() << " -> export " << Exports.size() << "\n"); 1248 Exports.push_back(Export); 1249 if (!WS.isExternal()) 1250 SymbolFlags.emplace_back(WS.getName(), wasm::WASM_SYMBOL_BINDING_LOCAL); 1251 } 1252 } 1253 1254 // Handle weak aliases. We need to process these in a separate pass because 1255 // we need to have processed the target of the alias before the alias itself 1256 // and the symbols are not necessarily ordered in this way. 1257 for (const MCSymbol &S : Asm.symbols()) { 1258 if (!S.isVariable()) 1259 continue; 1260 1261 assert(S.isDefined(/*SetUsed=*/false)); 1262 1263 // Find the target symbol of this weak alias and export that index 1264 const auto &WS = static_cast<const MCSymbolWasm &>(S); 1265 const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS); 1266 DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym << "'\n"); 1267 assert(SymbolIndices.count(ResolvedSym) > 0); 1268 uint32_t Index = SymbolIndices.find(ResolvedSym)->second; 1269 DEBUG(dbgs() << " -> index:" << Index << "\n"); 1270 1271 SymbolIndices[&WS] = Index; 1272 WasmExport Export; 1273 Export.FieldName = WS.getName(); 1274 Export.Index = Index; 1275 if (WS.isFunction()) 1276 Export.Kind = wasm::WASM_EXTERNAL_FUNCTION; 1277 else 1278 Export.Kind = wasm::WASM_EXTERNAL_GLOBAL; 1279 DEBUG(dbgs() << " -> export " << Exports.size() << "\n"); 1280 Exports.push_back(Export); 1281 1282 if (!WS.isExternal()) 1283 SymbolFlags.emplace_back(WS.getName(), wasm::WASM_SYMBOL_BINDING_LOCAL); 1284 } 1285 1286 // Add types for indirect function calls. 1287 for (const WasmRelocationEntry &Fixup : CodeRelocations) { 1288 if (Fixup.Type != wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) 1289 continue; 1290 1291 registerFunctionType(*Fixup.Symbol); 1292 } 1293 1294 // Write out the Wasm header. 1295 writeHeader(Asm); 1296 1297 writeTypeSection(FunctionTypes); 1298 writeImportSection(Imports); 1299 writeFunctionSection(Functions); 1300 writeTableSection(TableElems.size()); 1301 writeMemorySection(DataSize); 1302 writeGlobalSection(); 1303 writeExportSection(Exports); 1304 // TODO: Start Section 1305 writeElemSection(TableElems); 1306 writeCodeSection(Asm, Layout, Functions); 1307 writeDataSection(DataSegments); 1308 writeNameSection(Functions, Imports, NumFuncImports); 1309 writeCodeRelocSection(); 1310 writeDataRelocSection(); 1311 writeLinkingMetaDataSection(DataSegments, DataSize, DataAlignment, 1312 SymbolFlags, HasStackPointer, StackPointerGlobal); 1313 1314 // TODO: Translate the .comment section to the output. 1315 // TODO: Translate debug sections to the output. 1316 } 1317 1318 MCObjectWriter *llvm::createWasmObjectWriter(MCWasmObjectTargetWriter *MOTW, 1319 raw_pwrite_stream &OS) { 1320 return new WasmObjectWriter(MOTW, OS); 1321 } 1322