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