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