1 //===- Writer.cpp ---------------------------------------------------------===// 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 #include "Writer.h" 10 #include "Config.h" 11 #include "InputChunks.h" 12 #include "InputElement.h" 13 #include "MapFile.h" 14 #include "OutputSections.h" 15 #include "OutputSegment.h" 16 #include "Relocations.h" 17 #include "SymbolTable.h" 18 #include "SyntheticSections.h" 19 #include "WriterUtils.h" 20 #include "lld/Common/CommonLinkerContext.h" 21 #include "lld/Common/Strings.h" 22 #include "llvm/ADT/DenseSet.h" 23 #include "llvm/ADT/SmallSet.h" 24 #include "llvm/ADT/SmallVector.h" 25 #include "llvm/ADT/StringMap.h" 26 #include "llvm/BinaryFormat/Wasm.h" 27 #include "llvm/BinaryFormat/WasmTraits.h" 28 #include "llvm/Support/FileOutputBuffer.h" 29 #include "llvm/Support/Format.h" 30 #include "llvm/Support/FormatVariadic.h" 31 #include "llvm/Support/LEB128.h" 32 #include "llvm/Support/Parallel.h" 33 34 #include <cstdarg> 35 #include <map> 36 37 #define DEBUG_TYPE "lld" 38 39 using namespace llvm; 40 using namespace llvm::wasm; 41 42 namespace lld { 43 namespace wasm { 44 static constexpr int stackAlignment = 16; 45 static constexpr int heapAlignment = 16; 46 47 namespace { 48 49 // The writer writes a SymbolTable result to a file. 50 class Writer { 51 public: 52 void run(); 53 54 private: 55 void openFile(); 56 57 bool needsPassiveInitialization(const OutputSegment *segment); 58 bool hasPassiveInitializedSegments(); 59 60 void createSyntheticInitFunctions(); 61 void createInitMemoryFunction(); 62 void createStartFunction(); 63 void createApplyDataRelocationsFunction(); 64 void createApplyGlobalRelocationsFunction(); 65 void createApplyGlobalTLSRelocationsFunction(); 66 void createCallCtorsFunction(); 67 void createInitTLSFunction(); 68 void createCommandExportWrappers(); 69 void createCommandExportWrapper(uint32_t functionIndex, DefinedFunction *f); 70 71 void assignIndexes(); 72 void populateSymtab(); 73 void populateProducers(); 74 void populateTargetFeatures(); 75 // populateTargetFeatures happens early on so some checks are delayed 76 // until imports and exports are finalized. There are run unstead 77 // in checkImportExportTargetFeatures 78 void checkImportExportTargetFeatures(); 79 void calculateInitFunctions(); 80 void calculateImports(); 81 void calculateExports(); 82 void calculateCustomSections(); 83 void calculateTypes(); 84 void createOutputSegments(); 85 OutputSegment *createOutputSegment(StringRef name); 86 void combineOutputSegments(); 87 void layoutMemory(); 88 void createHeader(); 89 90 void addSection(OutputSection *sec); 91 92 void addSections(); 93 94 void createCustomSections(); 95 void createSyntheticSections(); 96 void createSyntheticSectionsPostLayout(); 97 void finalizeSections(); 98 99 // Custom sections 100 void createRelocSections(); 101 102 void writeHeader(); 103 void writeSections(); 104 105 uint64_t fileSize = 0; 106 107 std::vector<WasmInitEntry> initFunctions; 108 llvm::StringMap<std::vector<InputChunk *>> customSectionMapping; 109 110 // Stable storage for command export wrapper function name strings. 111 std::list<std::string> commandExportWrapperNames; 112 113 // Elements that are used to construct the final output 114 std::string header; 115 std::vector<OutputSection *> outputSections; 116 117 std::unique_ptr<FileOutputBuffer> buffer; 118 119 std::vector<OutputSegment *> segments; 120 llvm::SmallDenseMap<StringRef, OutputSegment *> segmentMap; 121 }; 122 123 } // anonymous namespace 124 125 void Writer::calculateCustomSections() { 126 log("calculateCustomSections"); 127 bool stripDebug = config->stripDebug || config->stripAll; 128 for (ObjFile *file : symtab->objectFiles) { 129 for (InputChunk *section : file->customSections) { 130 // Exclude COMDAT sections that are not selected for inclusion 131 if (section->discarded) 132 continue; 133 StringRef name = section->name; 134 // These custom sections are known the linker and synthesized rather than 135 // blindly copied. 136 if (name == "linking" || name == "name" || name == "producers" || 137 name == "target_features" || name.startswith("reloc.")) 138 continue; 139 // These custom sections are generated by `clang -fembed-bitcode`. 140 // These are used by the rust toolchain to ship LTO data along with 141 // compiled object code, but they don't want this included in the linker 142 // output. 143 if (name == ".llvmbc" || name == ".llvmcmd") 144 continue; 145 // Strip debug section in that option was specified. 146 if (stripDebug && name.startswith(".debug_")) 147 continue; 148 // Otherwise include custom sections by default and concatenate their 149 // contents. 150 customSectionMapping[name].push_back(section); 151 } 152 } 153 } 154 155 void Writer::createCustomSections() { 156 log("createCustomSections"); 157 for (auto &pair : customSectionMapping) { 158 StringRef name = pair.first(); 159 LLVM_DEBUG(dbgs() << "createCustomSection: " << name << "\n"); 160 161 OutputSection *sec = make<CustomSection>(std::string(name), pair.second); 162 if (config->relocatable || config->emitRelocs) { 163 auto *sym = make<OutputSectionSymbol>(sec); 164 out.linkingSec->addToSymtab(sym); 165 sec->sectionSym = sym; 166 } 167 addSection(sec); 168 } 169 } 170 171 // Create relocations sections in the final output. 172 // These are only created when relocatable output is requested. 173 void Writer::createRelocSections() { 174 log("createRelocSections"); 175 // Don't use iterator here since we are adding to OutputSection 176 size_t origSize = outputSections.size(); 177 for (size_t i = 0; i < origSize; i++) { 178 LLVM_DEBUG(dbgs() << "check section " << i << "\n"); 179 OutputSection *sec = outputSections[i]; 180 181 // Count the number of needed sections. 182 uint32_t count = sec->getNumRelocations(); 183 if (!count) 184 continue; 185 186 StringRef name; 187 if (sec->type == WASM_SEC_DATA) 188 name = "reloc.DATA"; 189 else if (sec->type == WASM_SEC_CODE) 190 name = "reloc.CODE"; 191 else if (sec->type == WASM_SEC_CUSTOM) 192 name = saver().save("reloc." + sec->name); 193 else 194 llvm_unreachable( 195 "relocations only supported for code, data, or custom sections"); 196 197 addSection(make<RelocSection>(name, sec)); 198 } 199 } 200 201 void Writer::populateProducers() { 202 for (ObjFile *file : symtab->objectFiles) { 203 const WasmProducerInfo &info = file->getWasmObj()->getProducerInfo(); 204 out.producersSec->addInfo(info); 205 } 206 } 207 208 void Writer::writeHeader() { 209 memcpy(buffer->getBufferStart(), header.data(), header.size()); 210 } 211 212 void Writer::writeSections() { 213 uint8_t *buf = buffer->getBufferStart(); 214 parallelForEach(outputSections, [buf](OutputSection *s) { 215 assert(s->isNeeded()); 216 s->writeTo(buf); 217 }); 218 } 219 220 static void setGlobalPtr(DefinedGlobal *g, uint64_t memoryPtr) { 221 LLVM_DEBUG(dbgs() << "setGlobalPtr " << g->getName() << " -> " << memoryPtr << "\n"); 222 g->global->setPointerValue(memoryPtr); 223 } 224 225 // Fix the memory layout of the output binary. This assigns memory offsets 226 // to each of the input data sections as well as the explicit stack region. 227 // The default memory layout is as follows, from low to high. 228 // 229 // - initialized data (starting at Config->globalBase) 230 // - BSS data (not currently implemented in llvm) 231 // - explicit stack (Config->ZStackSize) 232 // - heap start / unallocated 233 // 234 // The --stack-first option means that stack is placed before any static data. 235 // This can be useful since it means that stack overflow traps immediately 236 // rather than overwriting global data, but also increases code size since all 237 // static data loads and stores requires larger offsets. 238 void Writer::layoutMemory() { 239 uint64_t memoryPtr = 0; 240 241 auto placeStack = [&]() { 242 if (config->relocatable || config->isPic) 243 return; 244 memoryPtr = alignTo(memoryPtr, stackAlignment); 245 if (config->zStackSize != alignTo(config->zStackSize, stackAlignment)) 246 error("stack size must be " + Twine(stackAlignment) + "-byte aligned"); 247 log("mem: stack size = " + Twine(config->zStackSize)); 248 log("mem: stack base = " + Twine(memoryPtr)); 249 memoryPtr += config->zStackSize; 250 setGlobalPtr(cast<DefinedGlobal>(WasmSym::stackPointer), memoryPtr); 251 log("mem: stack top = " + Twine(memoryPtr)); 252 }; 253 254 if (config->stackFirst) { 255 placeStack(); 256 } else { 257 memoryPtr = config->globalBase; 258 log("mem: global base = " + Twine(config->globalBase)); 259 } 260 261 if (WasmSym::globalBase) 262 WasmSym::globalBase->setVA(memoryPtr); 263 264 uint64_t dataStart = memoryPtr; 265 266 // Arbitrarily set __dso_handle handle to point to the start of the data 267 // segments. 268 if (WasmSym::dsoHandle) 269 WasmSym::dsoHandle->setVA(dataStart); 270 271 out.dylinkSec->memAlign = 0; 272 for (OutputSegment *seg : segments) { 273 out.dylinkSec->memAlign = std::max(out.dylinkSec->memAlign, seg->alignment); 274 memoryPtr = alignTo(memoryPtr, 1ULL << seg->alignment); 275 seg->startVA = memoryPtr; 276 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", seg->name, 277 memoryPtr, seg->size, seg->alignment)); 278 279 if (!config->relocatable && seg->isTLS()) { 280 if (WasmSym::tlsSize) { 281 auto *tlsSize = cast<DefinedGlobal>(WasmSym::tlsSize); 282 setGlobalPtr(tlsSize, seg->size); 283 } 284 if (WasmSym::tlsAlign) { 285 auto *tlsAlign = cast<DefinedGlobal>(WasmSym::tlsAlign); 286 setGlobalPtr(tlsAlign, int64_t{1} << seg->alignment); 287 } 288 if (!config->sharedMemory && WasmSym::tlsBase) { 289 auto *tlsBase = cast<DefinedGlobal>(WasmSym::tlsBase); 290 setGlobalPtr(tlsBase, memoryPtr); 291 } 292 } 293 294 memoryPtr += seg->size; 295 } 296 297 // Make space for the memory initialization flag 298 if (config->sharedMemory && hasPassiveInitializedSegments()) { 299 memoryPtr = alignTo(memoryPtr, 4); 300 WasmSym::initMemoryFlag = symtab->addSyntheticDataSymbol( 301 "__wasm_init_memory_flag", WASM_SYMBOL_VISIBILITY_HIDDEN); 302 WasmSym::initMemoryFlag->markLive(); 303 WasmSym::initMemoryFlag->setVA(memoryPtr); 304 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", 305 "__wasm_init_memory_flag", memoryPtr, 4, 4)); 306 memoryPtr += 4; 307 } 308 309 if (WasmSym::dataEnd) 310 WasmSym::dataEnd->setVA(memoryPtr); 311 312 uint64_t staticDataSize = memoryPtr - dataStart; 313 log("mem: static data = " + Twine(staticDataSize)); 314 if (config->isPic) 315 out.dylinkSec->memSize = staticDataSize; 316 317 if (!config->stackFirst) 318 placeStack(); 319 320 if (WasmSym::heapBase) { 321 // Set `__heap_base` to follow the end of the stack or global data. The 322 // fact that this comes last means that a malloc/brk implementation can 323 // grow the heap at runtime. 324 // We'll align the heap base here because memory allocators might expect 325 // __heap_base to be aligned already. 326 memoryPtr = alignTo(memoryPtr, heapAlignment); 327 log("mem: heap base = " + Twine(memoryPtr)); 328 WasmSym::heapBase->setVA(memoryPtr); 329 } 330 331 uint64_t maxMemorySetting = 1ULL << (config->is64.value_or(false) ? 48 : 32); 332 333 if (config->initialMemory != 0) { 334 if (config->initialMemory != alignTo(config->initialMemory, WasmPageSize)) 335 error("initial memory must be " + Twine(WasmPageSize) + "-byte aligned"); 336 if (memoryPtr > config->initialMemory) 337 error("initial memory too small, " + Twine(memoryPtr) + " bytes needed"); 338 if (config->initialMemory > maxMemorySetting) 339 error("initial memory too large, cannot be greater than " + 340 Twine(maxMemorySetting)); 341 memoryPtr = config->initialMemory; 342 } 343 out.memorySec->numMemoryPages = 344 alignTo(memoryPtr, WasmPageSize) / WasmPageSize; 345 log("mem: total pages = " + Twine(out.memorySec->numMemoryPages)); 346 347 if (config->maxMemory != 0) { 348 if (config->maxMemory != alignTo(config->maxMemory, WasmPageSize)) 349 error("maximum memory must be " + Twine(WasmPageSize) + "-byte aligned"); 350 if (memoryPtr > config->maxMemory) 351 error("maximum memory too small, " + Twine(memoryPtr) + " bytes needed"); 352 if (config->maxMemory > maxMemorySetting) 353 error("maximum memory too large, cannot be greater than " + 354 Twine(maxMemorySetting)); 355 } 356 357 // Check max if explicitly supplied or required by shared memory 358 if (config->maxMemory != 0 || config->sharedMemory) { 359 uint64_t max = config->maxMemory; 360 if (max == 0) { 361 // If no maxMemory config was supplied but we are building with 362 // shared memory, we need to pick a sensible upper limit. 363 if (config->isPic) 364 max = maxMemorySetting; 365 else 366 max = alignTo(memoryPtr, WasmPageSize); 367 } 368 out.memorySec->maxMemoryPages = max / WasmPageSize; 369 log("mem: max pages = " + Twine(out.memorySec->maxMemoryPages)); 370 } 371 } 372 373 void Writer::addSection(OutputSection *sec) { 374 if (!sec->isNeeded()) 375 return; 376 log("addSection: " + toString(*sec)); 377 sec->sectionIndex = outputSections.size(); 378 outputSections.push_back(sec); 379 } 380 381 // If a section name is valid as a C identifier (which is rare because of 382 // the leading '.'), linkers are expected to define __start_<secname> and 383 // __stop_<secname> symbols. They are at beginning and end of the section, 384 // respectively. This is not requested by the ELF standard, but GNU ld and 385 // gold provide the feature, and used by many programs. 386 static void addStartStopSymbols(const OutputSegment *seg) { 387 StringRef name = seg->name; 388 if (!isValidCIdentifier(name)) 389 return; 390 LLVM_DEBUG(dbgs() << "addStartStopSymbols: " << name << "\n"); 391 uint64_t start = seg->startVA; 392 uint64_t stop = start + seg->size; 393 symtab->addOptionalDataSymbol(saver().save("__start_" + name), start); 394 symtab->addOptionalDataSymbol(saver().save("__stop_" + name), stop); 395 } 396 397 void Writer::addSections() { 398 addSection(out.dylinkSec); 399 addSection(out.typeSec); 400 addSection(out.importSec); 401 addSection(out.functionSec); 402 addSection(out.tableSec); 403 addSection(out.memorySec); 404 addSection(out.tagSec); 405 addSection(out.globalSec); 406 addSection(out.exportSec); 407 addSection(out.startSec); 408 addSection(out.elemSec); 409 addSection(out.dataCountSec); 410 411 addSection(make<CodeSection>(out.functionSec->inputFunctions)); 412 addSection(make<DataSection>(segments)); 413 414 createCustomSections(); 415 416 addSection(out.linkingSec); 417 if (config->emitRelocs || config->relocatable) { 418 createRelocSections(); 419 } 420 421 addSection(out.nameSec); 422 addSection(out.producersSec); 423 addSection(out.targetFeaturesSec); 424 } 425 426 void Writer::finalizeSections() { 427 for (OutputSection *s : outputSections) { 428 s->setOffset(fileSize); 429 s->finalizeContents(); 430 fileSize += s->getSize(); 431 } 432 } 433 434 void Writer::populateTargetFeatures() { 435 StringMap<std::string> used; 436 StringMap<std::string> required; 437 StringMap<std::string> disallowed; 438 SmallSet<std::string, 8> &allowed = out.targetFeaturesSec->features; 439 bool tlsUsed = false; 440 441 if (config->isPic) { 442 // This should not be necessary because all PIC objects should 443 // contain the mutable-globals feature. 444 // TODO(https://bugs.llvm.org/show_bug.cgi?id=52339) 445 allowed.insert("mutable-globals"); 446 } 447 448 // Only infer used features if user did not specify features 449 bool inferFeatures = !config->features.hasValue(); 450 451 if (!inferFeatures) { 452 auto &explicitFeatures = config->features.getValue(); 453 allowed.insert(explicitFeatures.begin(), explicitFeatures.end()); 454 if (!config->checkFeatures) 455 goto done; 456 } 457 458 // Find the sets of used, required, and disallowed features 459 for (ObjFile *file : symtab->objectFiles) { 460 StringRef fileName(file->getName()); 461 for (auto &feature : file->getWasmObj()->getTargetFeatures()) { 462 switch (feature.Prefix) { 463 case WASM_FEATURE_PREFIX_USED: 464 used.insert({feature.Name, std::string(fileName)}); 465 break; 466 case WASM_FEATURE_PREFIX_REQUIRED: 467 used.insert({feature.Name, std::string(fileName)}); 468 required.insert({feature.Name, std::string(fileName)}); 469 break; 470 case WASM_FEATURE_PREFIX_DISALLOWED: 471 disallowed.insert({feature.Name, std::string(fileName)}); 472 break; 473 default: 474 error("Unrecognized feature policy prefix " + 475 std::to_string(feature.Prefix)); 476 } 477 } 478 479 // Find TLS data segments 480 auto isTLS = [](InputChunk *segment) { 481 return segment->live && segment->isTLS(); 482 }; 483 tlsUsed = tlsUsed || llvm::any_of(file->segments, isTLS); 484 } 485 486 if (inferFeatures) 487 for (const auto &key : used.keys()) 488 allowed.insert(std::string(key)); 489 490 if (!config->checkFeatures) 491 goto done; 492 493 if (config->sharedMemory) { 494 if (disallowed.count("shared-mem")) 495 error("--shared-memory is disallowed by " + disallowed["shared-mem"] + 496 " because it was not compiled with 'atomics' or 'bulk-memory' " 497 "features."); 498 499 for (auto feature : {"atomics", "bulk-memory"}) 500 if (!allowed.count(feature)) 501 error(StringRef("'") + feature + 502 "' feature must be used in order to use shared memory"); 503 } 504 505 if (tlsUsed) { 506 for (auto feature : {"atomics", "bulk-memory"}) 507 if (!allowed.count(feature)) 508 error(StringRef("'") + feature + 509 "' feature must be used in order to use thread-local storage"); 510 } 511 512 // Validate that used features are allowed in output 513 if (!inferFeatures) { 514 for (const auto &feature : used.keys()) { 515 if (!allowed.count(std::string(feature))) 516 error(Twine("Target feature '") + feature + "' used by " + 517 used[feature] + " is not allowed."); 518 } 519 } 520 521 // Validate the required and disallowed constraints for each file 522 for (ObjFile *file : symtab->objectFiles) { 523 StringRef fileName(file->getName()); 524 SmallSet<std::string, 8> objectFeatures; 525 for (const auto &feature : file->getWasmObj()->getTargetFeatures()) { 526 if (feature.Prefix == WASM_FEATURE_PREFIX_DISALLOWED) 527 continue; 528 objectFeatures.insert(feature.Name); 529 if (disallowed.count(feature.Name)) 530 error(Twine("Target feature '") + feature.Name + "' used in " + 531 fileName + " is disallowed by " + disallowed[feature.Name] + 532 ". Use --no-check-features to suppress."); 533 } 534 for (const auto &feature : required.keys()) { 535 if (!objectFeatures.count(std::string(feature))) 536 error(Twine("Missing target feature '") + feature + "' in " + fileName + 537 ", required by " + required[feature] + 538 ". Use --no-check-features to suppress."); 539 } 540 } 541 542 done: 543 // Normally we don't include bss segments in the binary. In particular if 544 // memory is not being imported then we can assume its zero initialized. 545 // In the case the memory is imported, and we can use the memory.fill 546 // instruction, then we can also avoid including the segments. 547 if (config->importMemory && !allowed.count("bulk-memory")) 548 config->emitBssSegments = true; 549 550 if (allowed.count("extended-const")) 551 config->extendedConst = true; 552 553 for (auto &feature : allowed) 554 log("Allowed feature: " + feature); 555 } 556 557 void Writer::checkImportExportTargetFeatures() { 558 if (config->relocatable || !config->checkFeatures) 559 return; 560 561 if (out.targetFeaturesSec->features.count("mutable-globals") == 0) { 562 for (const Symbol *sym : out.importSec->importedSymbols) { 563 if (auto *global = dyn_cast<GlobalSymbol>(sym)) { 564 if (global->getGlobalType()->Mutable) { 565 error(Twine("mutable global imported but 'mutable-globals' feature " 566 "not present in inputs: `") + 567 toString(*sym) + "`. Use --no-check-features to suppress."); 568 } 569 } 570 } 571 for (const Symbol *sym : out.exportSec->exportedSymbols) { 572 if (isa<GlobalSymbol>(sym)) { 573 error(Twine("mutable global exported but 'mutable-globals' feature " 574 "not present in inputs: `") + 575 toString(*sym) + "`. Use --no-check-features to suppress."); 576 } 577 } 578 } 579 } 580 581 static bool shouldImport(Symbol *sym) { 582 // We don't generate imports for data symbols. They however can be imported 583 // as GOT entries. 584 if (isa<DataSymbol>(sym)) 585 return false; 586 if (!sym->isLive()) 587 return false; 588 if (!sym->isUsedInRegularObj) 589 return false; 590 591 // When a symbol is weakly defined in a shared library we need to allow 592 // it to be overridden by another module so need to both import 593 // and export the symbol. 594 if (config->shared && sym->isWeak() && !sym->isUndefined() && 595 !sym->isHidden()) 596 return true; 597 if (!sym->isUndefined()) 598 return false; 599 if (sym->isWeak() && !config->relocatable && !config->isPic) 600 return false; 601 602 // In PIC mode we only need to import functions when they are called directly. 603 // Indirect usage all goes via GOT imports. 604 if (config->isPic) { 605 if (auto *f = dyn_cast<UndefinedFunction>(sym)) 606 if (!f->isCalledDirectly) 607 return false; 608 } 609 610 if (config->isPic || config->relocatable || config->importUndefined || 611 config->unresolvedSymbols == UnresolvedPolicy::ImportDynamic) 612 return true; 613 if (config->allowUndefinedSymbols.count(sym->getName()) != 0) 614 return true; 615 616 return sym->importName.has_value(); 617 } 618 619 void Writer::calculateImports() { 620 // Some inputs require that the indirect function table be assigned to table 621 // number 0, so if it is present and is an import, allocate it before any 622 // other tables. 623 if (WasmSym::indirectFunctionTable && 624 shouldImport(WasmSym::indirectFunctionTable)) 625 out.importSec->addImport(WasmSym::indirectFunctionTable); 626 627 for (Symbol *sym : symtab->getSymbols()) { 628 if (!shouldImport(sym)) 629 continue; 630 if (sym == WasmSym::indirectFunctionTable) 631 continue; 632 LLVM_DEBUG(dbgs() << "import: " << sym->getName() << "\n"); 633 out.importSec->addImport(sym); 634 } 635 } 636 637 void Writer::calculateExports() { 638 if (config->relocatable) 639 return; 640 641 if (!config->relocatable && !config->importMemory) 642 out.exportSec->exports.push_back( 643 WasmExport{"memory", WASM_EXTERNAL_MEMORY, 0}); 644 645 unsigned globalIndex = 646 out.importSec->getNumImportedGlobals() + out.globalSec->numGlobals(); 647 648 for (Symbol *sym : symtab->getSymbols()) { 649 if (!sym->isExported()) 650 continue; 651 if (!sym->isLive()) 652 continue; 653 654 StringRef name = sym->getName(); 655 WasmExport export_; 656 if (auto *f = dyn_cast<DefinedFunction>(sym)) { 657 if (Optional<StringRef> exportName = f->function->getExportName()) { 658 name = *exportName; 659 } 660 export_ = {name, WASM_EXTERNAL_FUNCTION, f->getExportedFunctionIndex()}; 661 } else if (auto *g = dyn_cast<DefinedGlobal>(sym)) { 662 if (g->getGlobalType()->Mutable && !g->getFile() && !g->forceExport) { 663 // Avoid exporting mutable globals are linker synthesized (e.g. 664 // __stack_pointer or __tls_base) unless they are explicitly exported 665 // from the command line. 666 // Without this check `--export-all` would cause any program using the 667 // stack pointer to export a mutable global even if none of the input 668 // files were built with the `mutable-globals` feature. 669 continue; 670 } 671 export_ = {name, WASM_EXTERNAL_GLOBAL, g->getGlobalIndex()}; 672 } else if (auto *t = dyn_cast<DefinedTag>(sym)) { 673 export_ = {name, WASM_EXTERNAL_TAG, t->getTagIndex()}; 674 } else if (auto *d = dyn_cast<DefinedData>(sym)) { 675 out.globalSec->dataAddressGlobals.push_back(d); 676 export_ = {name, WASM_EXTERNAL_GLOBAL, globalIndex++}; 677 } else { 678 auto *t = cast<DefinedTable>(sym); 679 export_ = {name, WASM_EXTERNAL_TABLE, t->getTableNumber()}; 680 } 681 682 LLVM_DEBUG(dbgs() << "Export: " << name << "\n"); 683 out.exportSec->exports.push_back(export_); 684 out.exportSec->exportedSymbols.push_back(sym); 685 } 686 } 687 688 void Writer::populateSymtab() { 689 if (!config->relocatable && !config->emitRelocs) 690 return; 691 692 for (Symbol *sym : symtab->getSymbols()) 693 if (sym->isUsedInRegularObj && sym->isLive()) 694 out.linkingSec->addToSymtab(sym); 695 696 for (ObjFile *file : symtab->objectFiles) { 697 LLVM_DEBUG(dbgs() << "Local symtab entries: " << file->getName() << "\n"); 698 for (Symbol *sym : file->getSymbols()) 699 if (sym->isLocal() && !isa<SectionSymbol>(sym) && sym->isLive()) 700 out.linkingSec->addToSymtab(sym); 701 } 702 } 703 704 void Writer::calculateTypes() { 705 // The output type section is the union of the following sets: 706 // 1. Any signature used in the TYPE relocation 707 // 2. The signatures of all imported functions 708 // 3. The signatures of all defined functions 709 // 4. The signatures of all imported tags 710 // 5. The signatures of all defined tags 711 712 for (ObjFile *file : symtab->objectFiles) { 713 ArrayRef<WasmSignature> types = file->getWasmObj()->types(); 714 for (uint32_t i = 0; i < types.size(); i++) 715 if (file->typeIsUsed[i]) 716 file->typeMap[i] = out.typeSec->registerType(types[i]); 717 } 718 719 for (const Symbol *sym : out.importSec->importedSymbols) { 720 if (auto *f = dyn_cast<FunctionSymbol>(sym)) 721 out.typeSec->registerType(*f->signature); 722 else if (auto *t = dyn_cast<TagSymbol>(sym)) 723 out.typeSec->registerType(*t->signature); 724 } 725 726 for (const InputFunction *f : out.functionSec->inputFunctions) 727 out.typeSec->registerType(f->signature); 728 729 for (const InputTag *t : out.tagSec->inputTags) 730 out.typeSec->registerType(t->signature); 731 } 732 733 // In a command-style link, create a wrapper for each exported symbol 734 // which calls the constructors and destructors. 735 void Writer::createCommandExportWrappers() { 736 // This logic doesn't currently support Emscripten-style PIC mode. 737 assert(!config->isPic); 738 739 // If there are no ctors and there's no libc `__wasm_call_dtors` to 740 // call, don't wrap the exports. 741 if (initFunctions.empty() && WasmSym::callDtors == nullptr) 742 return; 743 744 std::vector<DefinedFunction *> toWrap; 745 746 for (Symbol *sym : symtab->getSymbols()) 747 if (sym->isExported()) 748 if (auto *f = dyn_cast<DefinedFunction>(sym)) 749 toWrap.push_back(f); 750 751 for (auto *f : toWrap) { 752 auto funcNameStr = (f->getName() + ".command_export").str(); 753 commandExportWrapperNames.push_back(funcNameStr); 754 const std::string &funcName = commandExportWrapperNames.back(); 755 756 auto func = make<SyntheticFunction>(*f->getSignature(), funcName); 757 if (f->function->getExportName()) 758 func->setExportName(f->function->getExportName()->str()); 759 else 760 func->setExportName(f->getName().str()); 761 762 DefinedFunction *def = 763 symtab->addSyntheticFunction(funcName, f->flags, func); 764 def->markLive(); 765 766 def->flags |= WASM_SYMBOL_EXPORTED; 767 def->flags &= ~WASM_SYMBOL_VISIBILITY_HIDDEN; 768 def->forceExport = f->forceExport; 769 770 f->flags |= WASM_SYMBOL_VISIBILITY_HIDDEN; 771 f->flags &= ~WASM_SYMBOL_EXPORTED; 772 f->forceExport = false; 773 774 out.functionSec->addFunction(func); 775 776 createCommandExportWrapper(f->getFunctionIndex(), def); 777 } 778 } 779 780 static void finalizeIndirectFunctionTable() { 781 if (!WasmSym::indirectFunctionTable) 782 return; 783 784 if (shouldImport(WasmSym::indirectFunctionTable) && 785 !WasmSym::indirectFunctionTable->hasTableNumber()) { 786 // Processing -Bsymbolic relocations resulted in a late requirement that the 787 // indirect function table be present, and we are running in --import-table 788 // mode. Add the table now to the imports section. Otherwise it will be 789 // added to the tables section later in assignIndexes. 790 out.importSec->addImport(WasmSym::indirectFunctionTable); 791 } 792 793 uint32_t tableSize = config->tableBase + out.elemSec->numEntries(); 794 WasmLimits limits = {0, tableSize, 0}; 795 if (WasmSym::indirectFunctionTable->isDefined() && !config->growableTable) { 796 limits.Flags |= WASM_LIMITS_FLAG_HAS_MAX; 797 limits.Maximum = limits.Minimum; 798 } 799 WasmSym::indirectFunctionTable->setLimits(limits); 800 } 801 802 static void scanRelocations() { 803 for (ObjFile *file : symtab->objectFiles) { 804 LLVM_DEBUG(dbgs() << "scanRelocations: " << file->getName() << "\n"); 805 for (InputChunk *chunk : file->functions) 806 scanRelocations(chunk); 807 for (InputChunk *chunk : file->segments) 808 scanRelocations(chunk); 809 for (auto &p : file->customSections) 810 scanRelocations(p); 811 } 812 } 813 814 void Writer::assignIndexes() { 815 // Seal the import section, since other index spaces such as function and 816 // global are effected by the number of imports. 817 out.importSec->seal(); 818 819 for (InputFunction *func : symtab->syntheticFunctions) 820 out.functionSec->addFunction(func); 821 822 for (ObjFile *file : symtab->objectFiles) { 823 LLVM_DEBUG(dbgs() << "Functions: " << file->getName() << "\n"); 824 for (InputFunction *func : file->functions) 825 out.functionSec->addFunction(func); 826 } 827 828 for (InputGlobal *global : symtab->syntheticGlobals) 829 out.globalSec->addGlobal(global); 830 831 for (ObjFile *file : symtab->objectFiles) { 832 LLVM_DEBUG(dbgs() << "Globals: " << file->getName() << "\n"); 833 for (InputGlobal *global : file->globals) 834 out.globalSec->addGlobal(global); 835 } 836 837 for (ObjFile *file : symtab->objectFiles) { 838 LLVM_DEBUG(dbgs() << "Tags: " << file->getName() << "\n"); 839 for (InputTag *tag : file->tags) 840 out.tagSec->addTag(tag); 841 } 842 843 for (ObjFile *file : symtab->objectFiles) { 844 LLVM_DEBUG(dbgs() << "Tables: " << file->getName() << "\n"); 845 for (InputTable *table : file->tables) 846 out.tableSec->addTable(table); 847 } 848 849 for (InputTable *table : symtab->syntheticTables) 850 out.tableSec->addTable(table); 851 852 out.globalSec->assignIndexes(); 853 out.tableSec->assignIndexes(); 854 } 855 856 static StringRef getOutputDataSegmentName(const InputChunk &seg) { 857 // We always merge .tbss and .tdata into a single TLS segment so all TLS 858 // symbols are be relative to single __tls_base. 859 if (seg.isTLS()) 860 return ".tdata"; 861 if (!config->mergeDataSegments) 862 return seg.name; 863 if (seg.name.startswith(".text.")) 864 return ".text"; 865 if (seg.name.startswith(".data.")) 866 return ".data"; 867 if (seg.name.startswith(".bss.")) 868 return ".bss"; 869 if (seg.name.startswith(".rodata.")) 870 return ".rodata"; 871 return seg.name; 872 } 873 874 OutputSegment *Writer::createOutputSegment(StringRef name) { 875 LLVM_DEBUG(dbgs() << "new segment: " << name << "\n"); 876 OutputSegment *s = make<OutputSegment>(name); 877 if (config->sharedMemory) 878 s->initFlags = WASM_DATA_SEGMENT_IS_PASSIVE; 879 if (!config->relocatable && name.startswith(".bss")) 880 s->isBss = true; 881 segments.push_back(s); 882 return s; 883 } 884 885 void Writer::createOutputSegments() { 886 for (ObjFile *file : symtab->objectFiles) { 887 for (InputChunk *segment : file->segments) { 888 if (!segment->live) 889 continue; 890 StringRef name = getOutputDataSegmentName(*segment); 891 OutputSegment *s = nullptr; 892 // When running in relocatable mode we can't merge segments that are part 893 // of comdat groups since the ultimate linker needs to be able exclude or 894 // include them individually. 895 if (config->relocatable && !segment->getComdatName().empty()) { 896 s = createOutputSegment(name); 897 } else { 898 if (segmentMap.count(name) == 0) 899 segmentMap[name] = createOutputSegment(name); 900 s = segmentMap[name]; 901 } 902 s->addInputSegment(segment); 903 } 904 } 905 906 // Sort segments by type, placing .bss last 907 std::stable_sort(segments.begin(), segments.end(), 908 [](const OutputSegment *a, const OutputSegment *b) { 909 auto order = [](StringRef name) { 910 return StringSwitch<int>(name) 911 .StartsWith(".tdata", 0) 912 .StartsWith(".rodata", 1) 913 .StartsWith(".data", 2) 914 .StartsWith(".bss", 4) 915 .Default(3); 916 }; 917 return order(a->name) < order(b->name); 918 }); 919 920 for (size_t i = 0; i < segments.size(); ++i) 921 segments[i]->index = i; 922 923 // Merge MergeInputSections into a single MergeSyntheticSection. 924 LLVM_DEBUG(dbgs() << "-- finalize input semgments\n"); 925 for (OutputSegment *seg : segments) 926 seg->finalizeInputSegments(); 927 } 928 929 void Writer::combineOutputSegments() { 930 // With PIC code we currently only support a single active data segment since 931 // we only have a single __memory_base to use as our base address. This pass 932 // combines all data segments into a single .data segment. 933 // This restriction does not apply when the extended const extension is 934 // available: https://github.com/WebAssembly/extended-const 935 assert(!config->extendedConst); 936 assert(config->isPic && !config->sharedMemory); 937 if (segments.size() <= 1) 938 return; 939 OutputSegment *combined = make<OutputSegment>(".data"); 940 combined->startVA = segments[0]->startVA; 941 for (OutputSegment *s : segments) { 942 bool first = true; 943 for (InputChunk *inSeg : s->inputSegments) { 944 if (first) 945 inSeg->alignment = std::max(inSeg->alignment, s->alignment); 946 first = false; 947 #ifndef NDEBUG 948 uint64_t oldVA = inSeg->getVA(); 949 #endif 950 combined->addInputSegment(inSeg); 951 #ifndef NDEBUG 952 uint64_t newVA = inSeg->getVA(); 953 LLVM_DEBUG(dbgs() << "added input segment. name=" << inSeg->name 954 << " oldVA=" << oldVA << " newVA=" << newVA << "\n"); 955 assert(oldVA == newVA); 956 #endif 957 } 958 } 959 960 segments = {combined}; 961 } 962 963 static void createFunction(DefinedFunction *func, StringRef bodyContent) { 964 std::string functionBody; 965 { 966 raw_string_ostream os(functionBody); 967 writeUleb128(os, bodyContent.size(), "function size"); 968 os << bodyContent; 969 } 970 ArrayRef<uint8_t> body = arrayRefFromStringRef(saver().save(functionBody)); 971 cast<SyntheticFunction>(func->function)->setBody(body); 972 } 973 974 bool Writer::needsPassiveInitialization(const OutputSegment *segment) { 975 // If bulk memory features is supported then we can perform bss initialization 976 // (via memory.fill) during `__wasm_init_memory`. 977 if (config->importMemory && !segment->requiredInBinary()) 978 return true; 979 return segment->initFlags & WASM_DATA_SEGMENT_IS_PASSIVE; 980 } 981 982 bool Writer::hasPassiveInitializedSegments() { 983 return llvm::any_of(segments, [this](const OutputSegment *s) { 984 return this->needsPassiveInitialization(s); 985 }); 986 } 987 988 void Writer::createSyntheticInitFunctions() { 989 if (config->relocatable) 990 return; 991 992 static WasmSignature nullSignature = {{}, {}}; 993 994 // Passive segments are used to avoid memory being reinitialized on each 995 // thread's instantiation. These passive segments are initialized and 996 // dropped in __wasm_init_memory, which is registered as the start function 997 // We also initialize bss segments (using memory.fill) as part of this 998 // function. 999 if (hasPassiveInitializedSegments()) { 1000 WasmSym::initMemory = symtab->addSyntheticFunction( 1001 "__wasm_init_memory", WASM_SYMBOL_VISIBILITY_HIDDEN, 1002 make<SyntheticFunction>(nullSignature, "__wasm_init_memory")); 1003 WasmSym::initMemory->markLive(); 1004 if (config->sharedMemory) { 1005 // This global is assigned during __wasm_init_memory in the shared memory 1006 // case. 1007 WasmSym::tlsBase->markLive(); 1008 } 1009 } 1010 1011 if (config->sharedMemory && out.globalSec->needsTLSRelocations()) { 1012 WasmSym::applyGlobalTLSRelocs = symtab->addSyntheticFunction( 1013 "__wasm_apply_global_tls_relocs", WASM_SYMBOL_VISIBILITY_HIDDEN, 1014 make<SyntheticFunction>(nullSignature, 1015 "__wasm_apply_global_tls_relocs")); 1016 WasmSym::applyGlobalTLSRelocs->markLive(); 1017 // TLS relocations depend on the __tls_base symbols 1018 WasmSym::tlsBase->markLive(); 1019 } 1020 1021 if (config->isPic || 1022 config->unresolvedSymbols == UnresolvedPolicy::ImportDynamic) { 1023 // For PIC code, or when dynamically importing addresses, we create 1024 // synthetic functions that apply relocations. These get called from 1025 // __wasm_call_ctors before the user-level constructors. 1026 WasmSym::applyDataRelocs = symtab->addSyntheticFunction( 1027 "__wasm_apply_data_relocs", WASM_SYMBOL_VISIBILITY_HIDDEN, 1028 make<SyntheticFunction>(nullSignature, "__wasm_apply_data_relocs")); 1029 WasmSym::applyDataRelocs->markLive(); 1030 } 1031 1032 if (config->isPic && out.globalSec->needsRelocations()) { 1033 WasmSym::applyGlobalRelocs = symtab->addSyntheticFunction( 1034 "__wasm_apply_global_relocs", WASM_SYMBOL_VISIBILITY_HIDDEN, 1035 make<SyntheticFunction>(nullSignature, "__wasm_apply_global_relocs")); 1036 WasmSym::applyGlobalRelocs->markLive(); 1037 } 1038 1039 // If there is only one start function we can just use that function 1040 // itself as the Wasm start function, otherwise we need to synthesize 1041 // a new function to call them in sequence. 1042 if (WasmSym::applyGlobalRelocs && WasmSym::initMemory) { 1043 WasmSym::startFunction = symtab->addSyntheticFunction( 1044 "__wasm_start", WASM_SYMBOL_VISIBILITY_HIDDEN, 1045 make<SyntheticFunction>(nullSignature, "__wasm_start")); 1046 WasmSym::startFunction->markLive(); 1047 } 1048 } 1049 1050 void Writer::createInitMemoryFunction() { 1051 LLVM_DEBUG(dbgs() << "createInitMemoryFunction\n"); 1052 assert(WasmSym::initMemory); 1053 assert(hasPassiveInitializedSegments()); 1054 uint64_t flagAddress; 1055 if (config->sharedMemory) { 1056 assert(WasmSym::initMemoryFlag); 1057 flagAddress = WasmSym::initMemoryFlag->getVA(); 1058 } 1059 bool is64 = config->is64.value_or(false); 1060 std::string bodyContent; 1061 { 1062 raw_string_ostream os(bodyContent); 1063 // Initialize memory in a thread-safe manner. The thread that successfully 1064 // increments the flag from 0 to 1 is is responsible for performing the 1065 // memory initialization. Other threads go sleep on the flag until the 1066 // first thread finishing initializing memory, increments the flag to 2, 1067 // and wakes all the other threads. Once the flag has been set to 2, 1068 // subsequently started threads will skip the sleep. All threads 1069 // unconditionally drop their passive data segments once memory has been 1070 // initialized. The generated code is as follows: 1071 // 1072 // (func $__wasm_init_memory 1073 // (block $drop 1074 // (block $wait 1075 // (block $init 1076 // (br_table $init $wait $drop 1077 // (i32.atomic.rmw.cmpxchg align=2 offset=0 1078 // (i32.const $__init_memory_flag) 1079 // (i32.const 0) 1080 // (i32.const 1) 1081 // ) 1082 // ) 1083 // ) ;; $init 1084 // ( ... initialize data segments ... ) 1085 // (i32.atomic.store align=2 offset=0 1086 // (i32.const $__init_memory_flag) 1087 // (i32.const 2) 1088 // ) 1089 // (drop 1090 // (i32.atomic.notify align=2 offset=0 1091 // (i32.const $__init_memory_flag) 1092 // (i32.const -1u) 1093 // ) 1094 // ) 1095 // (br $drop) 1096 // ) ;; $wait 1097 // (drop 1098 // (i32.atomic.wait align=2 offset=0 1099 // (i32.const $__init_memory_flag) 1100 // (i32.const 1) 1101 // (i32.const -1) 1102 // ) 1103 // ) 1104 // ) ;; $drop 1105 // ( ... drop data segments ... ) 1106 // ) 1107 // 1108 // When we are building with PIC, calculate the flag location using: 1109 // 1110 // (global.get $__memory_base) 1111 // (i32.const $__init_memory_flag) 1112 // (i32.const 1) 1113 1114 auto writeGetFlagAddress = [&]() { 1115 if (config->isPic) { 1116 writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get"); 1117 writeUleb128(os, 0, "local 0"); 1118 } else { 1119 writePtrConst(os, flagAddress, is64, "flag address"); 1120 } 1121 }; 1122 1123 if (config->sharedMemory) { 1124 // With PIC code we cache the flag address in local 0 1125 if (config->isPic) { 1126 writeUleb128(os, 1, "num local decls"); 1127 writeUleb128(os, 2, "local count"); 1128 writeU8(os, is64 ? WASM_TYPE_I64 : WASM_TYPE_I32, "address type"); 1129 writeU8(os, WASM_OPCODE_GLOBAL_GET, "GLOBAL_GET"); 1130 writeUleb128(os, WasmSym::memoryBase->getGlobalIndex(), "memory_base"); 1131 writePtrConst(os, flagAddress, is64, "flag address"); 1132 writeU8(os, is64 ? WASM_OPCODE_I64_ADD : WASM_OPCODE_I32_ADD, "add"); 1133 writeU8(os, WASM_OPCODE_LOCAL_SET, "local.set"); 1134 writeUleb128(os, 0, "local 0"); 1135 } else { 1136 writeUleb128(os, 0, "num locals"); 1137 } 1138 1139 // Set up destination blocks 1140 writeU8(os, WASM_OPCODE_BLOCK, "block $drop"); 1141 writeU8(os, WASM_TYPE_NORESULT, "block type"); 1142 writeU8(os, WASM_OPCODE_BLOCK, "block $wait"); 1143 writeU8(os, WASM_TYPE_NORESULT, "block type"); 1144 writeU8(os, WASM_OPCODE_BLOCK, "block $init"); 1145 writeU8(os, WASM_TYPE_NORESULT, "block type"); 1146 1147 // Atomically check whether we win the race. 1148 writeGetFlagAddress(); 1149 writeI32Const(os, 0, "expected flag value"); 1150 writeI32Const(os, 1, "new flag value"); 1151 writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix"); 1152 writeUleb128(os, WASM_OPCODE_I32_RMW_CMPXCHG, "i32.atomic.rmw.cmpxchg"); 1153 writeMemArg(os, 2, 0); 1154 1155 // Based on the value, decide what to do next. 1156 writeU8(os, WASM_OPCODE_BR_TABLE, "br_table"); 1157 writeUleb128(os, 2, "label vector length"); 1158 writeUleb128(os, 0, "label $init"); 1159 writeUleb128(os, 1, "label $wait"); 1160 writeUleb128(os, 2, "default label $drop"); 1161 1162 // Initialize passive data segments 1163 writeU8(os, WASM_OPCODE_END, "end $init"); 1164 } else { 1165 writeUleb128(os, 0, "num local decls"); 1166 } 1167 1168 for (const OutputSegment *s : segments) { 1169 if (needsPassiveInitialization(s)) { 1170 // For passive BSS segments we can simple issue a memory.fill(0). 1171 // For non-BSS segments we do a memory.init. Both these 1172 // instructions take as their first argument the destination 1173 // address. 1174 writePtrConst(os, s->startVA, is64, "destination address"); 1175 if (config->isPic) { 1176 writeU8(os, WASM_OPCODE_GLOBAL_GET, "GLOBAL_GET"); 1177 writeUleb128(os, WasmSym::memoryBase->getGlobalIndex(), 1178 "__memory_base"); 1179 writeU8(os, is64 ? WASM_OPCODE_I64_ADD : WASM_OPCODE_I32_ADD, 1180 "i32.add"); 1181 } 1182 1183 // When we initialize the TLS segment we also set the `__tls_base` 1184 // global. This allows the runtime to use this static copy of the 1185 // TLS data for the first/main thread. 1186 if (config->sharedMemory && s->isTLS()) { 1187 if (config->isPic) { 1188 // Cache the result of the addionion in local 0 1189 writeU8(os, WASM_OPCODE_LOCAL_TEE, "local.tee"); 1190 writeUleb128(os, 1, "local 1"); 1191 } else { 1192 writePtrConst(os, s->startVA, is64, "destination address"); 1193 } 1194 writeU8(os, WASM_OPCODE_GLOBAL_SET, "GLOBAL_SET"); 1195 writeUleb128(os, WasmSym::tlsBase->getGlobalIndex(), 1196 "__tls_base"); 1197 if (config->isPic) { 1198 writeU8(os, WASM_OPCODE_LOCAL_GET, "local.tee"); 1199 writeUleb128(os, 1, "local 1"); 1200 } 1201 } 1202 1203 if (s->isBss) { 1204 writeI32Const(os, 0, "fill value"); 1205 writeI32Const(os, s->size, "memory region size"); 1206 writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix"); 1207 writeUleb128(os, WASM_OPCODE_MEMORY_FILL, "memory.fill"); 1208 writeU8(os, 0, "memory index immediate"); 1209 } else { 1210 writeI32Const(os, 0, "source segment offset"); 1211 writeI32Const(os, s->size, "memory region size"); 1212 writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix"); 1213 writeUleb128(os, WASM_OPCODE_MEMORY_INIT, "memory.init"); 1214 writeUleb128(os, s->index, "segment index immediate"); 1215 writeU8(os, 0, "memory index immediate"); 1216 } 1217 } 1218 } 1219 1220 if (config->sharedMemory) { 1221 // Set flag to 2 to mark end of initialization 1222 writeGetFlagAddress(); 1223 writeI32Const(os, 2, "flag value"); 1224 writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix"); 1225 writeUleb128(os, WASM_OPCODE_I32_ATOMIC_STORE, "i32.atomic.store"); 1226 writeMemArg(os, 2, 0); 1227 1228 // Notify any waiters that memory initialization is complete 1229 writeGetFlagAddress(); 1230 writeI32Const(os, -1, "number of waiters"); 1231 writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix"); 1232 writeUleb128(os, WASM_OPCODE_ATOMIC_NOTIFY, "atomic.notify"); 1233 writeMemArg(os, 2, 0); 1234 writeU8(os, WASM_OPCODE_DROP, "drop"); 1235 1236 // Branch to drop the segments 1237 writeU8(os, WASM_OPCODE_BR, "br"); 1238 writeUleb128(os, 1, "label $drop"); 1239 1240 // Wait for the winning thread to initialize memory 1241 writeU8(os, WASM_OPCODE_END, "end $wait"); 1242 writeGetFlagAddress(); 1243 writeI32Const(os, 1, "expected flag value"); 1244 writeI64Const(os, -1, "timeout"); 1245 1246 writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix"); 1247 writeUleb128(os, WASM_OPCODE_I32_ATOMIC_WAIT, "i32.atomic.wait"); 1248 writeMemArg(os, 2, 0); 1249 writeU8(os, WASM_OPCODE_DROP, "drop"); 1250 1251 // Unconditionally drop passive data segments 1252 writeU8(os, WASM_OPCODE_END, "end $drop"); 1253 } 1254 1255 for (const OutputSegment *s : segments) { 1256 if (needsPassiveInitialization(s) && !s->isBss) { 1257 // The TLS region should not be dropped since its is needed 1258 // during the initialization of each thread (__wasm_init_tls). 1259 if (config->sharedMemory && s->isTLS()) 1260 continue; 1261 // data.drop instruction 1262 writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix"); 1263 writeUleb128(os, WASM_OPCODE_DATA_DROP, "data.drop"); 1264 writeUleb128(os, s->index, "segment index immediate"); 1265 } 1266 } 1267 1268 // End the function 1269 writeU8(os, WASM_OPCODE_END, "END"); 1270 } 1271 1272 createFunction(WasmSym::initMemory, bodyContent); 1273 } 1274 1275 void Writer::createStartFunction() { 1276 // If the start function exists when we have more than one function to call. 1277 if (WasmSym::initMemory && WasmSym::applyGlobalRelocs) { 1278 assert(WasmSym::startFunction); 1279 std::string bodyContent; 1280 { 1281 raw_string_ostream os(bodyContent); 1282 writeUleb128(os, 0, "num locals"); 1283 writeU8(os, WASM_OPCODE_CALL, "CALL"); 1284 writeUleb128(os, WasmSym::applyGlobalRelocs->getFunctionIndex(), 1285 "function index"); 1286 writeU8(os, WASM_OPCODE_CALL, "CALL"); 1287 writeUleb128(os, WasmSym::initMemory->getFunctionIndex(), 1288 "function index"); 1289 writeU8(os, WASM_OPCODE_END, "END"); 1290 } 1291 createFunction(WasmSym::startFunction, bodyContent); 1292 } else if (WasmSym::initMemory) { 1293 WasmSym::startFunction = WasmSym::initMemory; 1294 } else if (WasmSym::applyGlobalRelocs) { 1295 WasmSym::startFunction = WasmSym::applyGlobalRelocs; 1296 } 1297 } 1298 1299 // For -shared (PIC) output, we create create a synthetic function which will 1300 // apply any relocations to the data segments on startup. This function is 1301 // called `__wasm_apply_data_relocs` and is added at the beginning of 1302 // `__wasm_call_ctors` before any of the constructors run. 1303 void Writer::createApplyDataRelocationsFunction() { 1304 LLVM_DEBUG(dbgs() << "createApplyDataRelocationsFunction\n"); 1305 // First write the body's contents to a string. 1306 std::string bodyContent; 1307 { 1308 raw_string_ostream os(bodyContent); 1309 writeUleb128(os, 0, "num locals"); 1310 for (const OutputSegment *seg : segments) 1311 for (const InputChunk *inSeg : seg->inputSegments) 1312 inSeg->generateRelocationCode(os); 1313 1314 writeU8(os, WASM_OPCODE_END, "END"); 1315 } 1316 1317 createFunction(WasmSym::applyDataRelocs, bodyContent); 1318 } 1319 1320 // Similar to createApplyDataRelocationsFunction but generates relocation code 1321 // for WebAssembly globals. Because these globals are not shared between threads 1322 // these relocation need to run on every thread. 1323 void Writer::createApplyGlobalRelocationsFunction() { 1324 // First write the body's contents to a string. 1325 std::string bodyContent; 1326 { 1327 raw_string_ostream os(bodyContent); 1328 writeUleb128(os, 0, "num locals"); 1329 out.globalSec->generateRelocationCode(os, false); 1330 writeU8(os, WASM_OPCODE_END, "END"); 1331 } 1332 1333 createFunction(WasmSym::applyGlobalRelocs, bodyContent); 1334 } 1335 1336 // Similar to createApplyGlobalRelocationsFunction but for 1337 // TLS symbols. This cannot be run during the start function 1338 // but must be delayed until __wasm_init_tls is called. 1339 void Writer::createApplyGlobalTLSRelocationsFunction() { 1340 // First write the body's contents to a string. 1341 std::string bodyContent; 1342 { 1343 raw_string_ostream os(bodyContent); 1344 writeUleb128(os, 0, "num locals"); 1345 out.globalSec->generateRelocationCode(os, true); 1346 writeU8(os, WASM_OPCODE_END, "END"); 1347 } 1348 1349 createFunction(WasmSym::applyGlobalTLSRelocs, bodyContent); 1350 } 1351 1352 // Create synthetic "__wasm_call_ctors" function based on ctor functions 1353 // in input object. 1354 void Writer::createCallCtorsFunction() { 1355 // If __wasm_call_ctors isn't referenced, there aren't any ctors, and we 1356 // aren't calling `__wasm_apply_data_relocs` for Emscripten-style PIC, don't 1357 // define the `__wasm_call_ctors` function. 1358 if (!WasmSym::callCtors->isLive() && !WasmSym::applyDataRelocs && 1359 initFunctions.empty()) 1360 return; 1361 1362 // First write the body's contents to a string. 1363 std::string bodyContent; 1364 { 1365 raw_string_ostream os(bodyContent); 1366 writeUleb128(os, 0, "num locals"); 1367 1368 if (WasmSym::applyDataRelocs) { 1369 writeU8(os, WASM_OPCODE_CALL, "CALL"); 1370 writeUleb128(os, WasmSym::applyDataRelocs->getFunctionIndex(), 1371 "function index"); 1372 } 1373 1374 // Call constructors 1375 for (const WasmInitEntry &f : initFunctions) { 1376 writeU8(os, WASM_OPCODE_CALL, "CALL"); 1377 writeUleb128(os, f.sym->getFunctionIndex(), "function index"); 1378 for (size_t i = 0; i < f.sym->signature->Returns.size(); i++) { 1379 writeU8(os, WASM_OPCODE_DROP, "DROP"); 1380 } 1381 } 1382 1383 writeU8(os, WASM_OPCODE_END, "END"); 1384 } 1385 1386 createFunction(WasmSym::callCtors, bodyContent); 1387 } 1388 1389 // Create a wrapper around a function export which calls the 1390 // static constructors and destructors. 1391 void Writer::createCommandExportWrapper(uint32_t functionIndex, 1392 DefinedFunction *f) { 1393 // First write the body's contents to a string. 1394 std::string bodyContent; 1395 { 1396 raw_string_ostream os(bodyContent); 1397 writeUleb128(os, 0, "num locals"); 1398 1399 // Call `__wasm_call_ctors` which call static constructors (and 1400 // applies any runtime relocations in Emscripten-style PIC mode) 1401 if (WasmSym::callCtors->isLive()) { 1402 writeU8(os, WASM_OPCODE_CALL, "CALL"); 1403 writeUleb128(os, WasmSym::callCtors->getFunctionIndex(), 1404 "function index"); 1405 } 1406 1407 // Call the user's code, leaving any return values on the operand stack. 1408 for (size_t i = 0; i < f->signature->Params.size(); ++i) { 1409 writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get"); 1410 writeUleb128(os, i, "local index"); 1411 } 1412 writeU8(os, WASM_OPCODE_CALL, "CALL"); 1413 writeUleb128(os, functionIndex, "function index"); 1414 1415 // Call the function that calls the destructors. 1416 if (DefinedFunction *callDtors = WasmSym::callDtors) { 1417 writeU8(os, WASM_OPCODE_CALL, "CALL"); 1418 writeUleb128(os, callDtors->getFunctionIndex(), "function index"); 1419 } 1420 1421 // End the function, returning the return values from the user's code. 1422 writeU8(os, WASM_OPCODE_END, "END"); 1423 } 1424 1425 createFunction(f, bodyContent); 1426 } 1427 1428 void Writer::createInitTLSFunction() { 1429 std::string bodyContent; 1430 { 1431 raw_string_ostream os(bodyContent); 1432 1433 OutputSegment *tlsSeg = nullptr; 1434 for (auto *seg : segments) { 1435 if (seg->name == ".tdata") { 1436 tlsSeg = seg; 1437 break; 1438 } 1439 } 1440 1441 writeUleb128(os, 0, "num locals"); 1442 if (tlsSeg) { 1443 writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get"); 1444 writeUleb128(os, 0, "local index"); 1445 1446 writeU8(os, WASM_OPCODE_GLOBAL_SET, "global.set"); 1447 writeUleb128(os, WasmSym::tlsBase->getGlobalIndex(), "global index"); 1448 1449 // FIXME(wvo): this local needs to be I64 in wasm64, or we need an extend op. 1450 writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get"); 1451 writeUleb128(os, 0, "local index"); 1452 1453 writeI32Const(os, 0, "segment offset"); 1454 1455 writeI32Const(os, tlsSeg->size, "memory region size"); 1456 1457 writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix"); 1458 writeUleb128(os, WASM_OPCODE_MEMORY_INIT, "MEMORY.INIT"); 1459 writeUleb128(os, tlsSeg->index, "segment index immediate"); 1460 writeU8(os, 0, "memory index immediate"); 1461 } 1462 1463 if (WasmSym::applyGlobalTLSRelocs) { 1464 writeU8(os, WASM_OPCODE_CALL, "CALL"); 1465 writeUleb128(os, WasmSym::applyGlobalTLSRelocs->getFunctionIndex(), 1466 "function index"); 1467 } 1468 writeU8(os, WASM_OPCODE_END, "end function"); 1469 } 1470 1471 createFunction(WasmSym::initTLS, bodyContent); 1472 } 1473 1474 // Populate InitFunctions vector with init functions from all input objects. 1475 // This is then used either when creating the output linking section or to 1476 // synthesize the "__wasm_call_ctors" function. 1477 void Writer::calculateInitFunctions() { 1478 if (!config->relocatable && !WasmSym::callCtors->isLive()) 1479 return; 1480 1481 for (ObjFile *file : symtab->objectFiles) { 1482 const WasmLinkingData &l = file->getWasmObj()->linkingData(); 1483 for (const WasmInitFunc &f : l.InitFunctions) { 1484 FunctionSymbol *sym = file->getFunctionSymbol(f.Symbol); 1485 // comdat exclusions can cause init functions be discarded. 1486 if (sym->isDiscarded() || !sym->isLive()) 1487 continue; 1488 if (sym->signature->Params.size() != 0) 1489 error("constructor functions cannot take arguments: " + toString(*sym)); 1490 LLVM_DEBUG(dbgs() << "initFunctions: " << toString(*sym) << "\n"); 1491 initFunctions.emplace_back(WasmInitEntry{sym, f.Priority}); 1492 } 1493 } 1494 1495 // Sort in order of priority (lowest first) so that they are called 1496 // in the correct order. 1497 llvm::stable_sort(initFunctions, 1498 [](const WasmInitEntry &l, const WasmInitEntry &r) { 1499 return l.priority < r.priority; 1500 }); 1501 } 1502 1503 void Writer::createSyntheticSections() { 1504 out.dylinkSec = make<DylinkSection>(); 1505 out.typeSec = make<TypeSection>(); 1506 out.importSec = make<ImportSection>(); 1507 out.functionSec = make<FunctionSection>(); 1508 out.tableSec = make<TableSection>(); 1509 out.memorySec = make<MemorySection>(); 1510 out.tagSec = make<TagSection>(); 1511 out.globalSec = make<GlobalSection>(); 1512 out.exportSec = make<ExportSection>(); 1513 out.startSec = make<StartSection>(); 1514 out.elemSec = make<ElemSection>(); 1515 out.producersSec = make<ProducersSection>(); 1516 out.targetFeaturesSec = make<TargetFeaturesSection>(); 1517 } 1518 1519 void Writer::createSyntheticSectionsPostLayout() { 1520 out.dataCountSec = make<DataCountSection>(segments); 1521 out.linkingSec = make<LinkingSection>(initFunctions, segments); 1522 out.nameSec = make<NameSection>(segments); 1523 } 1524 1525 void Writer::run() { 1526 if (config->relocatable || config->isPic) 1527 config->globalBase = 0; 1528 1529 // For PIC code the table base is assigned dynamically by the loader. 1530 // For non-PIC, we start at 1 so that accessing table index 0 always traps. 1531 if (!config->isPic) { 1532 config->tableBase = 1; 1533 if (WasmSym::definedTableBase) 1534 WasmSym::definedTableBase->setVA(config->tableBase); 1535 if (WasmSym::definedTableBase32) 1536 WasmSym::definedTableBase32->setVA(config->tableBase); 1537 } 1538 1539 log("-- createOutputSegments"); 1540 createOutputSegments(); 1541 log("-- createSyntheticSections"); 1542 createSyntheticSections(); 1543 log("-- layoutMemory"); 1544 layoutMemory(); 1545 1546 if (!config->relocatable) { 1547 // Create linker synthesized __start_SECNAME/__stop_SECNAME symbols 1548 // This has to be done after memory layout is performed. 1549 for (const OutputSegment *seg : segments) { 1550 addStartStopSymbols(seg); 1551 } 1552 } 1553 1554 for (auto &pair : config->exportedSymbols) { 1555 Symbol *sym = symtab->find(pair.first()); 1556 if (sym && sym->isDefined()) 1557 sym->forceExport = true; 1558 } 1559 1560 // Delay reporting error about explicit exports until after 1561 // addStartStopSymbols which can create optional symbols. 1562 for (auto &name : config->requiredExports) { 1563 Symbol *sym = symtab->find(name); 1564 if (!sym || !sym->isDefined()) { 1565 if (config->unresolvedSymbols == UnresolvedPolicy::ReportError) 1566 error(Twine("symbol exported via --export not found: ") + name); 1567 if (config->unresolvedSymbols == UnresolvedPolicy::Warn) 1568 warn(Twine("symbol exported via --export not found: ") + name); 1569 } 1570 } 1571 1572 log("-- populateTargetFeatures"); 1573 populateTargetFeatures(); 1574 1575 // When outputting PIC code each segment lives at at fixes offset from the 1576 // `__memory_base` import. Unless we support the extended const expression we 1577 // can't do addition inside the constant expression, so we much combine the 1578 // segments into a single one that can live at `__memory_base`. 1579 if (config->isPic && !config->extendedConst && !config->sharedMemory) { 1580 // In shared memory mode all data segments are passive and initialized 1581 // via __wasm_init_memory. 1582 log("-- combineOutputSegments"); 1583 combineOutputSegments(); 1584 } 1585 1586 log("-- createSyntheticSectionsPostLayout"); 1587 createSyntheticSectionsPostLayout(); 1588 log("-- populateProducers"); 1589 populateProducers(); 1590 log("-- calculateImports"); 1591 calculateImports(); 1592 log("-- scanRelocations"); 1593 scanRelocations(); 1594 log("-- finalizeIndirectFunctionTable"); 1595 finalizeIndirectFunctionTable(); 1596 log("-- createSyntheticInitFunctions"); 1597 createSyntheticInitFunctions(); 1598 log("-- assignIndexes"); 1599 assignIndexes(); 1600 log("-- calculateInitFunctions"); 1601 calculateInitFunctions(); 1602 1603 if (!config->relocatable) { 1604 // Create linker synthesized functions 1605 if (WasmSym::applyDataRelocs) 1606 createApplyDataRelocationsFunction(); 1607 if (WasmSym::applyGlobalRelocs) 1608 createApplyGlobalRelocationsFunction(); 1609 if (WasmSym::applyGlobalTLSRelocs) 1610 createApplyGlobalTLSRelocationsFunction(); 1611 if (WasmSym::initMemory) 1612 createInitMemoryFunction(); 1613 createStartFunction(); 1614 1615 createCallCtorsFunction(); 1616 1617 // Create export wrappers for commands if needed. 1618 // 1619 // If the input contains a call to `__wasm_call_ctors`, either in one of 1620 // the input objects or an explicit export from the command-line, we 1621 // assume ctors and dtors are taken care of already. 1622 if (!config->relocatable && !config->isPic && 1623 !WasmSym::callCtors->isUsedInRegularObj && 1624 !WasmSym::callCtors->isExported()) { 1625 log("-- createCommandExportWrappers"); 1626 createCommandExportWrappers(); 1627 } 1628 } 1629 1630 if (WasmSym::initTLS && WasmSym::initTLS->isLive()) { 1631 log("-- createInitTLSFunction"); 1632 createInitTLSFunction(); 1633 } 1634 1635 if (errorCount()) 1636 return; 1637 1638 log("-- calculateTypes"); 1639 calculateTypes(); 1640 log("-- calculateExports"); 1641 calculateExports(); 1642 log("-- calculateCustomSections"); 1643 calculateCustomSections(); 1644 log("-- populateSymtab"); 1645 populateSymtab(); 1646 log("-- checkImportExportTargetFeatures"); 1647 checkImportExportTargetFeatures(); 1648 log("-- addSections"); 1649 addSections(); 1650 1651 if (errorHandler().verbose) { 1652 log("Defined Functions: " + Twine(out.functionSec->inputFunctions.size())); 1653 log("Defined Globals : " + Twine(out.globalSec->numGlobals())); 1654 log("Defined Tags : " + Twine(out.tagSec->inputTags.size())); 1655 log("Defined Tables : " + Twine(out.tableSec->inputTables.size())); 1656 log("Function Imports : " + 1657 Twine(out.importSec->getNumImportedFunctions())); 1658 log("Global Imports : " + Twine(out.importSec->getNumImportedGlobals())); 1659 log("Tag Imports : " + Twine(out.importSec->getNumImportedTags())); 1660 log("Table Imports : " + Twine(out.importSec->getNumImportedTables())); 1661 } 1662 1663 createHeader(); 1664 log("-- finalizeSections"); 1665 finalizeSections(); 1666 1667 log("-- writeMapFile"); 1668 writeMapFile(outputSections); 1669 1670 log("-- openFile"); 1671 openFile(); 1672 if (errorCount()) 1673 return; 1674 1675 writeHeader(); 1676 1677 log("-- writeSections"); 1678 writeSections(); 1679 if (errorCount()) 1680 return; 1681 1682 if (Error e = buffer->commit()) 1683 fatal("failed to write the output file: " + toString(std::move(e))); 1684 } 1685 1686 // Open a result file. 1687 void Writer::openFile() { 1688 log("writing: " + config->outputFile); 1689 1690 Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr = 1691 FileOutputBuffer::create(config->outputFile, fileSize, 1692 FileOutputBuffer::F_executable); 1693 1694 if (!bufferOrErr) 1695 error("failed to open " + config->outputFile + ": " + 1696 toString(bufferOrErr.takeError())); 1697 else 1698 buffer = std::move(*bufferOrErr); 1699 } 1700 1701 void Writer::createHeader() { 1702 raw_string_ostream os(header); 1703 writeBytes(os, WasmMagic, sizeof(WasmMagic), "wasm magic"); 1704 writeU32(os, WasmVersion, "wasm version"); 1705 os.flush(); 1706 fileSize += header.size(); 1707 } 1708 1709 void writeResult() { Writer().run(); } 1710 1711 } // namespace wasm 1712 } // namespace lld 1713