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