1 //===- Writer.cpp ---------------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "Writer.h" 10 #include "Config.h" 11 #include "InputChunks.h" 12 #include "InputElement.h" 13 #include "MapFile.h" 14 #include "OutputSections.h" 15 #include "OutputSegment.h" 16 #include "Relocations.h" 17 #include "SymbolTable.h" 18 #include "SyntheticSections.h" 19 #include "WriterUtils.h" 20 #include "lld/Common/CommonLinkerContext.h" 21 #include "lld/Common/Strings.h" 22 #include "llvm/ADT/DenseSet.h" 23 #include "llvm/ADT/SmallSet.h" 24 #include "llvm/ADT/SmallVector.h" 25 #include "llvm/ADT/StringMap.h" 26 #include "llvm/BinaryFormat/Wasm.h" 27 #include "llvm/BinaryFormat/WasmTraits.h" 28 #include "llvm/Support/FileOutputBuffer.h" 29 #include "llvm/Support/Format.h" 30 #include "llvm/Support/FormatVariadic.h" 31 #include "llvm/Support/LEB128.h" 32 #include "llvm/Support/Parallel.h" 33 34 #include <cstdarg> 35 #include <map> 36 37 #define DEBUG_TYPE "lld" 38 39 using namespace llvm; 40 using namespace llvm::wasm; 41 42 namespace lld { 43 namespace wasm { 44 static constexpr int stackAlignment = 16; 45 static constexpr int heapAlignment = 16; 46 47 namespace { 48 49 // The writer writes a SymbolTable result to a file. 50 class Writer { 51 public: 52 void run(); 53 54 private: 55 void openFile(); 56 57 bool needsPassiveInitialization(const OutputSegment *segment); 58 bool hasPassiveInitializedSegments(); 59 60 void createSyntheticInitFunctions(); 61 void createInitMemoryFunction(); 62 void createStartFunction(); 63 void createApplyDataRelocationsFunction(); 64 void createApplyGlobalRelocationsFunction(); 65 void createApplyGlobalTLSRelocationsFunction(); 66 void createCallCtorsFunction(); 67 void createInitTLSFunction(); 68 void createCommandExportWrappers(); 69 void createCommandExportWrapper(uint32_t functionIndex, DefinedFunction *f); 70 71 void assignIndexes(); 72 void populateSymtab(); 73 void populateProducers(); 74 void populateTargetFeatures(); 75 // populateTargetFeatures happens early on so some checks are delayed 76 // until imports and exports are finalized. There are run unstead 77 // in checkImportExportTargetFeatures 78 void checkImportExportTargetFeatures(); 79 void calculateInitFunctions(); 80 void calculateImports(); 81 void calculateExports(); 82 void calculateCustomSections(); 83 void calculateTypes(); 84 void createOutputSegments(); 85 OutputSegment *createOutputSegment(StringRef name); 86 void combineOutputSegments(); 87 void layoutMemory(); 88 void createHeader(); 89 90 void addSection(OutputSection *sec); 91 92 void addSections(); 93 94 void createCustomSections(); 95 void createSyntheticSections(); 96 void createSyntheticSectionsPostLayout(); 97 void finalizeSections(); 98 99 // Custom sections 100 void createRelocSections(); 101 102 void writeHeader(); 103 void writeSections(); 104 105 uint64_t fileSize = 0; 106 107 std::vector<WasmInitEntry> initFunctions; 108 llvm::StringMap<std::vector<InputChunk *>> customSectionMapping; 109 110 // Stable storage for command export wrapper function name strings. 111 std::list<std::string> commandExportWrapperNames; 112 113 // Elements that are used to construct the final output 114 std::string header; 115 std::vector<OutputSection *> outputSections; 116 117 std::unique_ptr<FileOutputBuffer> buffer; 118 119 std::vector<OutputSegment *> segments; 120 llvm::SmallDenseMap<StringRef, OutputSegment *> segmentMap; 121 }; 122 123 } // anonymous namespace 124 125 void Writer::calculateCustomSections() { 126 log("calculateCustomSections"); 127 bool stripDebug = config->stripDebug || config->stripAll; 128 for (ObjFile *file : symtab->objectFiles) { 129 for (InputChunk *section : file->customSections) { 130 // Exclude COMDAT sections that are not selected for inclusion 131 if (section->discarded) 132 continue; 133 StringRef name = section->name; 134 // These custom sections are known the linker and synthesized rather than 135 // blindly copied. 136 if (name == "linking" || name == "name" || name == "producers" || 137 name == "target_features" || name.startswith("reloc.")) 138 continue; 139 // These custom sections are generated by `clang -fembed-bitcode`. 140 // These are used by the rust toolchain to ship LTO data along with 141 // compiled object code, but they don't want this included in the linker 142 // output. 143 if (name == ".llvmbc" || name == ".llvmcmd") 144 continue; 145 // Strip debug section in that option was specified. 146 if (stripDebug && name.startswith(".debug_")) 147 continue; 148 // Otherwise include custom sections by default and concatenate their 149 // contents. 150 customSectionMapping[name].push_back(section); 151 } 152 } 153 } 154 155 void Writer::createCustomSections() { 156 log("createCustomSections"); 157 for (auto &pair : customSectionMapping) { 158 StringRef name = pair.first(); 159 LLVM_DEBUG(dbgs() << "createCustomSection: " << name << "\n"); 160 161 OutputSection *sec = make<CustomSection>(std::string(name), pair.second); 162 if (config->relocatable || config->emitRelocs) { 163 auto *sym = make<OutputSectionSymbol>(sec); 164 out.linkingSec->addToSymtab(sym); 165 sec->sectionSym = sym; 166 } 167 addSection(sec); 168 } 169 } 170 171 // Create relocations sections in the final output. 172 // These are only created when relocatable output is requested. 173 void Writer::createRelocSections() { 174 log("createRelocSections"); 175 // Don't use iterator here since we are adding to OutputSection 176 size_t origSize = outputSections.size(); 177 for (size_t i = 0; i < origSize; i++) { 178 LLVM_DEBUG(dbgs() << "check section " << i << "\n"); 179 OutputSection *sec = outputSections[i]; 180 181 // Count the number of needed sections. 182 uint32_t count = sec->getNumRelocations(); 183 if (!count) 184 continue; 185 186 StringRef name; 187 if (sec->type == WASM_SEC_DATA) 188 name = "reloc.DATA"; 189 else if (sec->type == WASM_SEC_CODE) 190 name = "reloc.CODE"; 191 else if (sec->type == WASM_SEC_CUSTOM) 192 name = saver().save("reloc." + sec->name); 193 else 194 llvm_unreachable( 195 "relocations only supported for code, data, or custom sections"); 196 197 addSection(make<RelocSection>(name, sec)); 198 } 199 } 200 201 void Writer::populateProducers() { 202 for (ObjFile *file : symtab->objectFiles) { 203 const WasmProducerInfo &info = file->getWasmObj()->getProducerInfo(); 204 out.producersSec->addInfo(info); 205 } 206 } 207 208 void Writer::writeHeader() { 209 memcpy(buffer->getBufferStart(), header.data(), header.size()); 210 } 211 212 void Writer::writeSections() { 213 uint8_t *buf = buffer->getBufferStart(); 214 parallelForEach(outputSections, [buf](OutputSection *s) { 215 assert(s->isNeeded()); 216 s->writeTo(buf); 217 }); 218 } 219 220 static void setGlobalPtr(DefinedGlobal *g, uint64_t memoryPtr) { 221 LLVM_DEBUG(dbgs() << "setGlobalPtr " << g->getName() << " -> " << memoryPtr << "\n"); 222 g->global->setPointerValue(memoryPtr); 223 } 224 225 // Fix the memory layout of the output binary. This assigns memory offsets 226 // to each of the input data sections as well as the explicit stack region. 227 // The default memory layout is as follows, from low to high. 228 // 229 // - initialized data (starting at Config->globalBase) 230 // - BSS data (not currently implemented in llvm) 231 // - explicit stack (Config->ZStackSize) 232 // - heap start / unallocated 233 // 234 // The --stack-first option means that stack is placed before any static data. 235 // This can be useful since it means that stack overflow traps immediately 236 // rather than overwriting global data, but also increases code size since all 237 // static data loads and stores requires larger offsets. 238 void Writer::layoutMemory() { 239 uint64_t memoryPtr = 0; 240 241 auto placeStack = [&]() { 242 if (config->relocatable || config->isPic) 243 return; 244 memoryPtr = alignTo(memoryPtr, stackAlignment); 245 if (config->zStackSize != alignTo(config->zStackSize, stackAlignment)) 246 error("stack size must be " + Twine(stackAlignment) + "-byte aligned"); 247 log("mem: stack size = " + Twine(config->zStackSize)); 248 log("mem: stack base = " + Twine(memoryPtr)); 249 memoryPtr += config->zStackSize; 250 setGlobalPtr(cast<DefinedGlobal>(WasmSym::stackPointer), memoryPtr); 251 log("mem: stack top = " + Twine(memoryPtr)); 252 }; 253 254 if (config->stackFirst) { 255 placeStack(); 256 } else { 257 memoryPtr = config->globalBase; 258 log("mem: global base = " + Twine(config->globalBase)); 259 } 260 261 if (WasmSym::globalBase) 262 WasmSym::globalBase->setVA(memoryPtr); 263 264 uint64_t dataStart = memoryPtr; 265 266 // Arbitrarily set __dso_handle handle to point to the start of the data 267 // segments. 268 if (WasmSym::dsoHandle) 269 WasmSym::dsoHandle->setVA(dataStart); 270 271 out.dylinkSec->memAlign = 0; 272 for (OutputSegment *seg : segments) { 273 out.dylinkSec->memAlign = std::max(out.dylinkSec->memAlign, seg->alignment); 274 memoryPtr = alignTo(memoryPtr, 1ULL << seg->alignment); 275 seg->startVA = memoryPtr; 276 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", seg->name, 277 memoryPtr, seg->size, seg->alignment)); 278 279 if (!config->relocatable && seg->isTLS()) { 280 if (WasmSym::tlsSize) { 281 auto *tlsSize = cast<DefinedGlobal>(WasmSym::tlsSize); 282 setGlobalPtr(tlsSize, seg->size); 283 } 284 if (WasmSym::tlsAlign) { 285 auto *tlsAlign = cast<DefinedGlobal>(WasmSym::tlsAlign); 286 setGlobalPtr(tlsAlign, int64_t{1} << seg->alignment); 287 } 288 if (!config->sharedMemory && WasmSym::tlsBase) { 289 auto *tlsBase = cast<DefinedGlobal>(WasmSym::tlsBase); 290 setGlobalPtr(tlsBase, memoryPtr); 291 } 292 } 293 294 memoryPtr += seg->size; 295 } 296 297 // Make space for the memory initialization flag 298 if (config->sharedMemory && hasPassiveInitializedSegments()) { 299 memoryPtr = alignTo(memoryPtr, 4); 300 WasmSym::initMemoryFlag = symtab->addSyntheticDataSymbol( 301 "__wasm_init_memory_flag", WASM_SYMBOL_VISIBILITY_HIDDEN); 302 WasmSym::initMemoryFlag->markLive(); 303 WasmSym::initMemoryFlag->setVA(memoryPtr); 304 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", 305 "__wasm_init_memory_flag", memoryPtr, 4, 4)); 306 memoryPtr += 4; 307 } 308 309 if (WasmSym::dataEnd) 310 WasmSym::dataEnd->setVA(memoryPtr); 311 312 uint64_t staticDataSize = memoryPtr - dataStart; 313 log("mem: static data = " + Twine(staticDataSize)); 314 if (config->isPic) 315 out.dylinkSec->memSize = staticDataSize; 316 317 if (!config->stackFirst) 318 placeStack(); 319 320 if (WasmSym::heapBase) { 321 // Set `__heap_base` to follow the end of the stack or global data. The 322 // fact that this comes last means that a malloc/brk implementation can 323 // grow the heap at runtime. 324 // We'll align the heap base here because memory allocators might expect 325 // __heap_base to be aligned already. 326 memoryPtr = alignTo(memoryPtr, heapAlignment); 327 log("mem: heap base = " + Twine(memoryPtr)); 328 WasmSym::heapBase->setVA(memoryPtr); 329 } 330 331 uint64_t maxMemorySetting = 1ULL 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 if (!config->mergeDataSegments) 863 return seg.name; 864 if (seg.name.startswith(".text.")) 865 return ".text"; 866 if (seg.name.startswith(".data.")) 867 return ".data"; 868 if (seg.name.startswith(".bss.")) 869 return ".bss"; 870 if (seg.name.startswith(".rodata.")) 871 return ".rodata"; 872 return seg.name; 873 } 874 875 OutputSegment *Writer::createOutputSegment(StringRef name) { 876 LLVM_DEBUG(dbgs() << "new segment: " << name << "\n"); 877 OutputSegment *s = make<OutputSegment>(name); 878 if (config->sharedMemory) 879 s->initFlags = WASM_DATA_SEGMENT_IS_PASSIVE; 880 if (!config->relocatable && name.startswith(".bss")) 881 s->isBss = true; 882 segments.push_back(s); 883 return s; 884 } 885 886 void Writer::createOutputSegments() { 887 for (ObjFile *file : symtab->objectFiles) { 888 for (InputChunk *segment : file->segments) { 889 if (!segment->live) 890 continue; 891 StringRef name = getOutputDataSegmentName(*segment); 892 OutputSegment *s = nullptr; 893 // When running in relocatable mode we can't merge segments that are part 894 // of comdat groups since the ultimate linker needs to be able exclude or 895 // include them individually. 896 if (config->relocatable && !segment->getComdatName().empty()) { 897 s = createOutputSegment(name); 898 } else { 899 if (segmentMap.count(name) == 0) 900 segmentMap[name] = createOutputSegment(name); 901 s = segmentMap[name]; 902 } 903 s->addInputSegment(segment); 904 } 905 } 906 907 // Sort segments by type, placing .bss last 908 std::stable_sort(segments.begin(), segments.end(), 909 [](const OutputSegment *a, const OutputSegment *b) { 910 auto order = [](StringRef name) { 911 return StringSwitch<int>(name) 912 .StartsWith(".tdata", 0) 913 .StartsWith(".rodata", 1) 914 .StartsWith(".data", 2) 915 .StartsWith(".bss", 4) 916 .Default(3); 917 }; 918 return order(a->name) < order(b->name); 919 }); 920 921 for (size_t i = 0; i < segments.size(); ++i) 922 segments[i]->index = i; 923 924 // Merge MergeInputSections into a single MergeSyntheticSection. 925 LLVM_DEBUG(dbgs() << "-- finalize input semgments\n"); 926 for (OutputSegment *seg : segments) 927 seg->finalizeInputSegments(); 928 } 929 930 void Writer::combineOutputSegments() { 931 // With PIC code we currently only support a single active data segment since 932 // we only have a single __memory_base to use as our base address. This pass 933 // combines all data segments into a single .data segment. 934 // This restriction does not apply when the extended const extension is 935 // available: https://github.com/WebAssembly/extended-const 936 assert(!config->extendedConst); 937 assert(config->isPic && !config->sharedMemory); 938 if (segments.size() <= 1) 939 return; 940 OutputSegment *combined = make<OutputSegment>(".data"); 941 combined->startVA = segments[0]->startVA; 942 for (OutputSegment *s : segments) { 943 bool first = true; 944 for (InputChunk *inSeg : s->inputSegments) { 945 if (first) 946 inSeg->alignment = std::max(inSeg->alignment, s->alignment); 947 first = false; 948 #ifndef NDEBUG 949 uint64_t oldVA = inSeg->getVA(); 950 #endif 951 combined->addInputSegment(inSeg); 952 #ifndef NDEBUG 953 uint64_t newVA = inSeg->getVA(); 954 LLVM_DEBUG(dbgs() << "added input segment. name=" << inSeg->name 955 << " oldVA=" << oldVA << " newVA=" << newVA << "\n"); 956 assert(oldVA == newVA); 957 #endif 958 } 959 } 960 961 segments = {combined}; 962 } 963 964 static void createFunction(DefinedFunction *func, StringRef bodyContent) { 965 std::string functionBody; 966 { 967 raw_string_ostream os(functionBody); 968 writeUleb128(os, bodyContent.size(), "function size"); 969 os << bodyContent; 970 } 971 ArrayRef<uint8_t> body = arrayRefFromStringRef(saver().save(functionBody)); 972 cast<SyntheticFunction>(func->function)->setBody(body); 973 } 974 975 bool Writer::needsPassiveInitialization(const OutputSegment *segment) { 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 if (config->sharedMemory) { 1006 // This global is assigned during __wasm_init_memory in the shared memory 1007 // case. 1008 WasmSym::tlsBase->markLive(); 1009 } 1010 } 1011 1012 if (config->sharedMemory && out.globalSec->needsTLSRelocations()) { 1013 WasmSym::applyGlobalTLSRelocs = symtab->addSyntheticFunction( 1014 "__wasm_apply_global_tls_relocs", WASM_SYMBOL_VISIBILITY_HIDDEN, 1015 make<SyntheticFunction>(nullSignature, 1016 "__wasm_apply_global_tls_relocs")); 1017 WasmSym::applyGlobalTLSRelocs->markLive(); 1018 // TLS relocations depend on the __tls_base symbols 1019 WasmSym::tlsBase->markLive(); 1020 } 1021 1022 if (config->isPic || 1023 config->unresolvedSymbols == UnresolvedPolicy::ImportDynamic) { 1024 // For PIC code, or when dynamically importing addresses, we create 1025 // synthetic functions that apply relocations. These get called from 1026 // __wasm_call_ctors before the user-level constructors. 1027 WasmSym::applyDataRelocs = symtab->addSyntheticFunction( 1028 "__wasm_apply_data_relocs", WASM_SYMBOL_VISIBILITY_HIDDEN, 1029 make<SyntheticFunction>(nullSignature, "__wasm_apply_data_relocs")); 1030 WasmSym::applyDataRelocs->markLive(); 1031 } 1032 1033 if (config->isPic && out.globalSec->needsRelocations()) { 1034 WasmSym::applyGlobalRelocs = symtab->addSyntheticFunction( 1035 "__wasm_apply_global_relocs", WASM_SYMBOL_VISIBILITY_HIDDEN, 1036 make<SyntheticFunction>(nullSignature, "__wasm_apply_global_relocs")); 1037 WasmSym::applyGlobalRelocs->markLive(); 1038 } 1039 1040 int startCount = 0; 1041 if (WasmSym::applyGlobalRelocs) 1042 startCount++; 1043 if (WasmSym::WasmSym::initMemory || WasmSym::applyDataRelocs) 1044 startCount++; 1045 1046 // If there is only one start function we can just use that function 1047 // itself as the Wasm start function, otherwise we need to synthesize 1048 // a new function to call them in sequence. 1049 if (startCount > 1) { 1050 WasmSym::startFunction = symtab->addSyntheticFunction( 1051 "__wasm_start", WASM_SYMBOL_VISIBILITY_HIDDEN, 1052 make<SyntheticFunction>(nullSignature, "__wasm_start")); 1053 WasmSym::startFunction->markLive(); 1054 } 1055 } 1056 1057 void Writer::createInitMemoryFunction() { 1058 LLVM_DEBUG(dbgs() << "createInitMemoryFunction\n"); 1059 assert(WasmSym::initMemory); 1060 assert(hasPassiveInitializedSegments()); 1061 uint64_t flagAddress; 1062 if (config->sharedMemory) { 1063 assert(WasmSym::initMemoryFlag); 1064 flagAddress = WasmSym::initMemoryFlag->getVA(); 1065 } 1066 bool is64 = config->is64.getValueOr(false); 1067 std::string bodyContent; 1068 { 1069 raw_string_ostream os(bodyContent); 1070 // Initialize memory in a thread-safe manner. The thread that successfully 1071 // increments the flag from 0 to 1 is is responsible for performing the 1072 // memory initialization. Other threads go sleep on the flag until the 1073 // first thread finishing initializing memory, increments the flag to 2, 1074 // and wakes all the other threads. Once the flag has been set to 2, 1075 // subsequently started threads will skip the sleep. All threads 1076 // unconditionally drop their passive data segments once memory has been 1077 // initialized. The generated code is as follows: 1078 // 1079 // (func $__wasm_init_memory 1080 // (block $drop 1081 // (block $wait 1082 // (block $init 1083 // (br_table $init $wait $drop 1084 // (i32.atomic.rmw.cmpxchg align=2 offset=0 1085 // (i32.const $__init_memory_flag) 1086 // (i32.const 0) 1087 // (i32.const 1) 1088 // ) 1089 // ) 1090 // ) ;; $init 1091 // ( ... initialize data segments ... ) 1092 // (i32.atomic.store align=2 offset=0 1093 // (i32.const $__init_memory_flag) 1094 // (i32.const 2) 1095 // ) 1096 // (drop 1097 // (i32.atomic.notify align=2 offset=0 1098 // (i32.const $__init_memory_flag) 1099 // (i32.const -1u) 1100 // ) 1101 // ) 1102 // (br $drop) 1103 // ) ;; $wait 1104 // (drop 1105 // (i32.atomic.wait align=2 offset=0 1106 // (i32.const $__init_memory_flag) 1107 // (i32.const 1) 1108 // (i32.const -1) 1109 // ) 1110 // ) 1111 // ) ;; $drop 1112 // ( ... drop data segments ... ) 1113 // ) 1114 // 1115 // When we are building with PIC, calculate the flag location using: 1116 // 1117 // (global.get $__memory_base) 1118 // (i32.const $__init_memory_flag) 1119 // (i32.const 1) 1120 1121 auto writeGetFlagAddress = [&]() { 1122 if (config->isPic) { 1123 writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get"); 1124 writeUleb128(os, 0, "local 0"); 1125 } else { 1126 writePtrConst(os, flagAddress, is64, "flag address"); 1127 } 1128 }; 1129 1130 if (config->sharedMemory) { 1131 // With PIC code we cache the flag address in local 0 1132 if (config->isPic) { 1133 writeUleb128(os, 1, "num local decls"); 1134 writeUleb128(os, 2, "local count"); 1135 writeU8(os, is64 ? WASM_TYPE_I64 : WASM_TYPE_I32, "address type"); 1136 writeU8(os, WASM_OPCODE_GLOBAL_GET, "GLOBAL_GET"); 1137 writeUleb128(os, WasmSym::memoryBase->getGlobalIndex(), "memory_base"); 1138 writePtrConst(os, flagAddress, is64, "flag address"); 1139 writeU8(os, is64 ? WASM_OPCODE_I64_ADD : WASM_OPCODE_I32_ADD, "add"); 1140 writeU8(os, WASM_OPCODE_LOCAL_SET, "local.set"); 1141 writeUleb128(os, 0, "local 0"); 1142 } else { 1143 writeUleb128(os, 0, "num locals"); 1144 } 1145 1146 // Set up destination blocks 1147 writeU8(os, WASM_OPCODE_BLOCK, "block $drop"); 1148 writeU8(os, WASM_TYPE_NORESULT, "block type"); 1149 writeU8(os, WASM_OPCODE_BLOCK, "block $wait"); 1150 writeU8(os, WASM_TYPE_NORESULT, "block type"); 1151 writeU8(os, WASM_OPCODE_BLOCK, "block $init"); 1152 writeU8(os, WASM_TYPE_NORESULT, "block type"); 1153 1154 // Atomically check whether we win the race. 1155 writeGetFlagAddress(); 1156 writeI32Const(os, 0, "expected flag value"); 1157 writeI32Const(os, 1, "new flag value"); 1158 writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix"); 1159 writeUleb128(os, WASM_OPCODE_I32_RMW_CMPXCHG, "i32.atomic.rmw.cmpxchg"); 1160 writeMemArg(os, 2, 0); 1161 1162 // Based on the value, decide what to do next. 1163 writeU8(os, WASM_OPCODE_BR_TABLE, "br_table"); 1164 writeUleb128(os, 2, "label vector length"); 1165 writeUleb128(os, 0, "label $init"); 1166 writeUleb128(os, 1, "label $wait"); 1167 writeUleb128(os, 2, "default label $drop"); 1168 1169 // Initialize passive data segments 1170 writeU8(os, WASM_OPCODE_END, "end $init"); 1171 } else { 1172 writeUleb128(os, 0, "num local decls"); 1173 } 1174 1175 for (const OutputSegment *s : segments) { 1176 if (needsPassiveInitialization(s)) { 1177 // For passive BSS segments we can simple issue a memory.fill(0). 1178 // For non-BSS segments we do a memory.init. Both these 1179 // instructions take as thier first argument the destination 1180 // address. 1181 writePtrConst(os, s->startVA, is64, "destination address"); 1182 if (config->isPic) { 1183 writeU8(os, WASM_OPCODE_GLOBAL_GET, "GLOBAL_GET"); 1184 writeUleb128(os, WasmSym::memoryBase->getGlobalIndex(), 1185 "__memory_base"); 1186 writeU8(os, is64 ? WASM_OPCODE_I64_ADD : WASM_OPCODE_I32_ADD, 1187 "i32.add"); 1188 } 1189 1190 // When we initialize the TLS segment we also set the `__tls_base` 1191 // global. This allows the runtime to use this static copy of the 1192 // TLS data for the first/main thread. 1193 if (config->sharedMemory && s->isTLS()) { 1194 if (config->isPic) { 1195 // Cache the result of the addionion in local 0 1196 writeU8(os, WASM_OPCODE_LOCAL_TEE, "local.tee"); 1197 writeUleb128(os, 1, "local 1"); 1198 } else { 1199 writePtrConst(os, s->startVA, is64, "destination address"); 1200 } 1201 writeU8(os, WASM_OPCODE_GLOBAL_SET, "GLOBAL_SET"); 1202 writeUleb128(os, WasmSym::tlsBase->getGlobalIndex(), 1203 "__tls_base"); 1204 if (config->isPic) { 1205 writeU8(os, WASM_OPCODE_LOCAL_GET, "local.tee"); 1206 writeUleb128(os, 1, "local 1"); 1207 } 1208 } 1209 1210 if (s->isBss) { 1211 writeI32Const(os, 0, "fill value"); 1212 writeI32Const(os, s->size, "memory region size"); 1213 writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix"); 1214 writeUleb128(os, WASM_OPCODE_MEMORY_FILL, "memory.fill"); 1215 writeU8(os, 0, "memory index immediate"); 1216 } else { 1217 writeI32Const(os, 0, "source segment offset"); 1218 writeI32Const(os, s->size, "memory region size"); 1219 writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix"); 1220 writeUleb128(os, WASM_OPCODE_MEMORY_INIT, "memory.init"); 1221 writeUleb128(os, s->index, "segment index immediate"); 1222 writeU8(os, 0, "memory index immediate"); 1223 } 1224 } 1225 } 1226 1227 // Memory init is now complete. Apply data relocation if there 1228 // are any. 1229 if (WasmSym::applyDataRelocs) { 1230 writeU8(os, WASM_OPCODE_CALL, "CALL"); 1231 writeUleb128(os, WasmSym::applyDataRelocs->getFunctionIndex(), 1232 "function index"); 1233 } 1234 1235 if (config->sharedMemory) { 1236 // Set flag to 2 to mark end of initialization 1237 writeGetFlagAddress(); 1238 writeI32Const(os, 2, "flag value"); 1239 writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix"); 1240 writeUleb128(os, WASM_OPCODE_I32_ATOMIC_STORE, "i32.atomic.store"); 1241 writeMemArg(os, 2, 0); 1242 1243 // Notify any waiters that memory initialization is complete 1244 writeGetFlagAddress(); 1245 writeI32Const(os, -1, "number of waiters"); 1246 writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix"); 1247 writeUleb128(os, WASM_OPCODE_ATOMIC_NOTIFY, "atomic.notify"); 1248 writeMemArg(os, 2, 0); 1249 writeU8(os, WASM_OPCODE_DROP, "drop"); 1250 1251 // Branch to drop the segments 1252 writeU8(os, WASM_OPCODE_BR, "br"); 1253 writeUleb128(os, 1, "label $drop"); 1254 1255 // Wait for the winning thread to initialize memory 1256 writeU8(os, WASM_OPCODE_END, "end $wait"); 1257 writeGetFlagAddress(); 1258 writeI32Const(os, 1, "expected flag value"); 1259 writeI64Const(os, -1, "timeout"); 1260 1261 writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix"); 1262 writeUleb128(os, WASM_OPCODE_I32_ATOMIC_WAIT, "i32.atomic.wait"); 1263 writeMemArg(os, 2, 0); 1264 writeU8(os, WASM_OPCODE_DROP, "drop"); 1265 1266 // Unconditionally drop passive data segments 1267 writeU8(os, WASM_OPCODE_END, "end $drop"); 1268 } 1269 1270 for (const OutputSegment *s : segments) { 1271 if (needsPassiveInitialization(s) && !s->isBss) { 1272 // The TLS region should not be dropped since its is needed 1273 // during the intiailizing of each thread (__wasm_init_tls). 1274 if (config->sharedMemory && s->isTLS()) 1275 continue; 1276 // data.drop instruction 1277 writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix"); 1278 writeUleb128(os, WASM_OPCODE_DATA_DROP, "data.drop"); 1279 writeUleb128(os, s->index, "segment index immediate"); 1280 } 1281 } 1282 1283 // End the function 1284 writeU8(os, WASM_OPCODE_END, "END"); 1285 } 1286 1287 createFunction(WasmSym::initMemory, bodyContent); 1288 } 1289 1290 void Writer::createStartFunction() { 1291 // If the start function exists when we have more than one function to call. 1292 if (WasmSym::startFunction) { 1293 std::string bodyContent; 1294 { 1295 raw_string_ostream os(bodyContent); 1296 writeUleb128(os, 0, "num locals"); 1297 if (WasmSym::applyGlobalRelocs) { 1298 writeU8(os, WASM_OPCODE_CALL, "CALL"); 1299 writeUleb128(os, WasmSym::applyGlobalRelocs->getFunctionIndex(), 1300 "function index"); 1301 } 1302 if (WasmSym::initMemory) { 1303 writeU8(os, WASM_OPCODE_CALL, "CALL"); 1304 writeUleb128(os, WasmSym::initMemory->getFunctionIndex(), 1305 "function index"); 1306 } else if (WasmSym::applyDataRelocs) { 1307 // When initMemory is present it calls applyDataRelocs. If not, 1308 // we must call it directly. 1309 writeU8(os, WASM_OPCODE_CALL, "CALL"); 1310 writeUleb128(os, WasmSym::applyDataRelocs->getFunctionIndex(), 1311 "function index"); 1312 } 1313 writeU8(os, WASM_OPCODE_END, "END"); 1314 } 1315 createFunction(WasmSym::startFunction, bodyContent); 1316 } else if (WasmSym::initMemory) { 1317 WasmSym::startFunction = WasmSym::initMemory; 1318 } else if (WasmSym::applyGlobalRelocs) { 1319 WasmSym::startFunction = WasmSym::applyGlobalRelocs; 1320 } else if (WasmSym::applyDataRelocs) { 1321 WasmSym::startFunction = WasmSym::applyDataRelocs; 1322 } 1323 } 1324 1325 // For -shared (PIC) output, we create create a synthetic function which will 1326 // apply any relocations to the data segments on startup. This function is 1327 // called `__wasm_apply_data_relocs` and is added at the beginning of 1328 // `__wasm_call_ctors` before any of the constructors run. 1329 void Writer::createApplyDataRelocationsFunction() { 1330 LLVM_DEBUG(dbgs() << "createApplyDataRelocationsFunction\n"); 1331 // First write the body's contents to a string. 1332 std::string bodyContent; 1333 { 1334 raw_string_ostream os(bodyContent); 1335 writeUleb128(os, 0, "num locals"); 1336 for (const OutputSegment *seg : segments) 1337 for (const InputChunk *inSeg : seg->inputSegments) 1338 inSeg->generateRelocationCode(os); 1339 1340 writeU8(os, WASM_OPCODE_END, "END"); 1341 } 1342 1343 createFunction(WasmSym::applyDataRelocs, bodyContent); 1344 } 1345 1346 // Similar to createApplyDataRelocationsFunction but generates relocation code 1347 // for WebAssembly globals. Because these globals are not shared between threads 1348 // these relocation need to run on every thread. 1349 void Writer::createApplyGlobalRelocationsFunction() { 1350 // First write the body's contents to a string. 1351 std::string bodyContent; 1352 { 1353 raw_string_ostream os(bodyContent); 1354 writeUleb128(os, 0, "num locals"); 1355 out.globalSec->generateRelocationCode(os, false); 1356 writeU8(os, WASM_OPCODE_END, "END"); 1357 } 1358 1359 createFunction(WasmSym::applyGlobalRelocs, bodyContent); 1360 } 1361 1362 // Similar to createApplyGlobalRelocationsFunction but for 1363 // TLS symbols. This cannot be run during the start function 1364 // but must be delayed until __wasm_init_tls is called. 1365 void Writer::createApplyGlobalTLSRelocationsFunction() { 1366 // First write the body's contents to a string. 1367 std::string bodyContent; 1368 { 1369 raw_string_ostream os(bodyContent); 1370 writeUleb128(os, 0, "num locals"); 1371 out.globalSec->generateRelocationCode(os, true); 1372 writeU8(os, WASM_OPCODE_END, "END"); 1373 } 1374 1375 createFunction(WasmSym::applyGlobalTLSRelocs, bodyContent); 1376 } 1377 1378 // Create synthetic "__wasm_call_ctors" function based on ctor functions 1379 // in input object. 1380 void Writer::createCallCtorsFunction() { 1381 // If __wasm_call_ctors isn't referenced, there aren't any ctors, and we 1382 // aren't calling `__wasm_apply_data_relocs` for Emscripten-style PIC, don't 1383 // define the `__wasm_call_ctors` function. 1384 if (!WasmSym::callCtors->isLive() && initFunctions.empty()) 1385 return; 1386 1387 // First write the body's contents to a string. 1388 std::string bodyContent; 1389 { 1390 raw_string_ostream os(bodyContent); 1391 writeUleb128(os, 0, "num locals"); 1392 1393 if (WasmSym::applyDataRelocs && !WasmSym::initMemory) { 1394 writeU8(os, WASM_OPCODE_CALL, "CALL"); 1395 writeUleb128(os, WasmSym::applyDataRelocs->getFunctionIndex(), 1396 "function index"); 1397 } 1398 1399 // Call constructors 1400 for (const WasmInitEntry &f : initFunctions) { 1401 writeU8(os, WASM_OPCODE_CALL, "CALL"); 1402 writeUleb128(os, f.sym->getFunctionIndex(), "function index"); 1403 for (size_t i = 0; i < f.sym->signature->Returns.size(); i++) { 1404 writeU8(os, WASM_OPCODE_DROP, "DROP"); 1405 } 1406 } 1407 1408 writeU8(os, WASM_OPCODE_END, "END"); 1409 } 1410 1411 createFunction(WasmSym::callCtors, bodyContent); 1412 } 1413 1414 // Create a wrapper around a function export which calls the 1415 // static constructors and destructors. 1416 void Writer::createCommandExportWrapper(uint32_t functionIndex, 1417 DefinedFunction *f) { 1418 // First write the body's contents to a string. 1419 std::string bodyContent; 1420 { 1421 raw_string_ostream os(bodyContent); 1422 writeUleb128(os, 0, "num locals"); 1423 1424 // Call `__wasm_call_ctors` which call static constructors (and 1425 // applies any runtime relocations in Emscripten-style PIC mode) 1426 if (WasmSym::callCtors->isLive()) { 1427 writeU8(os, WASM_OPCODE_CALL, "CALL"); 1428 writeUleb128(os, WasmSym::callCtors->getFunctionIndex(), 1429 "function index"); 1430 } 1431 1432 // Call the user's code, leaving any return values on the operand stack. 1433 for (size_t i = 0; i < f->signature->Params.size(); ++i) { 1434 writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get"); 1435 writeUleb128(os, i, "local index"); 1436 } 1437 writeU8(os, WASM_OPCODE_CALL, "CALL"); 1438 writeUleb128(os, functionIndex, "function index"); 1439 1440 // Call the function that calls the destructors. 1441 if (DefinedFunction *callDtors = WasmSym::callDtors) { 1442 writeU8(os, WASM_OPCODE_CALL, "CALL"); 1443 writeUleb128(os, callDtors->getFunctionIndex(), "function index"); 1444 } 1445 1446 // End the function, returning the return values from the user's code. 1447 writeU8(os, WASM_OPCODE_END, "END"); 1448 } 1449 1450 createFunction(f, bodyContent); 1451 } 1452 1453 void Writer::createInitTLSFunction() { 1454 std::string bodyContent; 1455 { 1456 raw_string_ostream os(bodyContent); 1457 1458 OutputSegment *tlsSeg = nullptr; 1459 for (auto *seg : segments) { 1460 if (seg->name == ".tdata") { 1461 tlsSeg = seg; 1462 break; 1463 } 1464 } 1465 1466 writeUleb128(os, 0, "num locals"); 1467 if (tlsSeg) { 1468 writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get"); 1469 writeUleb128(os, 0, "local index"); 1470 1471 writeU8(os, WASM_OPCODE_GLOBAL_SET, "global.set"); 1472 writeUleb128(os, WasmSym::tlsBase->getGlobalIndex(), "global index"); 1473 1474 // FIXME(wvo): this local needs to be I64 in wasm64, or we need an extend op. 1475 writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get"); 1476 writeUleb128(os, 0, "local index"); 1477 1478 writeI32Const(os, 0, "segment offset"); 1479 1480 writeI32Const(os, tlsSeg->size, "memory region size"); 1481 1482 writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix"); 1483 writeUleb128(os, WASM_OPCODE_MEMORY_INIT, "MEMORY.INIT"); 1484 writeUleb128(os, tlsSeg->index, "segment index immediate"); 1485 writeU8(os, 0, "memory index immediate"); 1486 } 1487 1488 if (WasmSym::applyGlobalTLSRelocs) { 1489 writeU8(os, WASM_OPCODE_CALL, "CALL"); 1490 writeUleb128(os, WasmSym::applyGlobalTLSRelocs->getFunctionIndex(), 1491 "function index"); 1492 } 1493 writeU8(os, WASM_OPCODE_END, "end function"); 1494 } 1495 1496 createFunction(WasmSym::initTLS, bodyContent); 1497 } 1498 1499 // Populate InitFunctions vector with init functions from all input objects. 1500 // This is then used either when creating the output linking section or to 1501 // synthesize the "__wasm_call_ctors" function. 1502 void Writer::calculateInitFunctions() { 1503 if (!config->relocatable && !WasmSym::callCtors->isLive()) 1504 return; 1505 1506 for (ObjFile *file : symtab->objectFiles) { 1507 const WasmLinkingData &l = file->getWasmObj()->linkingData(); 1508 for (const WasmInitFunc &f : l.InitFunctions) { 1509 FunctionSymbol *sym = file->getFunctionSymbol(f.Symbol); 1510 // comdat exclusions can cause init functions be discarded. 1511 if (sym->isDiscarded() || !sym->isLive()) 1512 continue; 1513 if (sym->signature->Params.size() != 0) 1514 error("constructor functions cannot take arguments: " + toString(*sym)); 1515 LLVM_DEBUG(dbgs() << "initFunctions: " << toString(*sym) << "\n"); 1516 initFunctions.emplace_back(WasmInitEntry{sym, f.Priority}); 1517 } 1518 } 1519 1520 // Sort in order of priority (lowest first) so that they are called 1521 // in the correct order. 1522 llvm::stable_sort(initFunctions, 1523 [](const WasmInitEntry &l, const WasmInitEntry &r) { 1524 return l.priority < r.priority; 1525 }); 1526 } 1527 1528 void Writer::createSyntheticSections() { 1529 out.dylinkSec = make<DylinkSection>(); 1530 out.typeSec = make<TypeSection>(); 1531 out.importSec = make<ImportSection>(); 1532 out.functionSec = make<FunctionSection>(); 1533 out.tableSec = make<TableSection>(); 1534 out.memorySec = make<MemorySection>(); 1535 out.tagSec = make<TagSection>(); 1536 out.globalSec = make<GlobalSection>(); 1537 out.exportSec = make<ExportSection>(); 1538 out.startSec = make<StartSection>(); 1539 out.elemSec = make<ElemSection>(); 1540 out.producersSec = make<ProducersSection>(); 1541 out.targetFeaturesSec = make<TargetFeaturesSection>(); 1542 } 1543 1544 void Writer::createSyntheticSectionsPostLayout() { 1545 out.dataCountSec = make<DataCountSection>(segments); 1546 out.linkingSec = make<LinkingSection>(initFunctions, segments); 1547 out.nameSec = make<NameSection>(segments); 1548 } 1549 1550 void Writer::run() { 1551 if (config->relocatable || config->isPic) 1552 config->globalBase = 0; 1553 1554 // For PIC code the table base is assigned dynamically by the loader. 1555 // For non-PIC, we start at 1 so that accessing table index 0 always traps. 1556 if (!config->isPic) { 1557 config->tableBase = 1; 1558 if (WasmSym::definedTableBase) 1559 WasmSym::definedTableBase->setVA(config->tableBase); 1560 if (WasmSym::definedTableBase32) 1561 WasmSym::definedTableBase32->setVA(config->tableBase); 1562 } 1563 1564 log("-- createOutputSegments"); 1565 createOutputSegments(); 1566 log("-- createSyntheticSections"); 1567 createSyntheticSections(); 1568 log("-- layoutMemory"); 1569 layoutMemory(); 1570 1571 if (!config->relocatable) { 1572 // Create linker synthesized __start_SECNAME/__stop_SECNAME symbols 1573 // This has to be done after memory layout is performed. 1574 for (const OutputSegment *seg : segments) { 1575 addStartStopSymbols(seg); 1576 } 1577 } 1578 1579 for (auto &pair : config->exportedSymbols) { 1580 Symbol *sym = symtab->find(pair.first()); 1581 if (sym && sym->isDefined()) 1582 sym->forceExport = true; 1583 } 1584 1585 // Delay reporting error about explicit exports until after 1586 // addStartStopSymbols which can create optional symbols. 1587 for (auto &name : config->requiredExports) { 1588 Symbol *sym = symtab->find(name); 1589 if (!sym || !sym->isDefined()) { 1590 if (config->unresolvedSymbols == UnresolvedPolicy::ReportError) 1591 error(Twine("symbol exported via --export not found: ") + name); 1592 if (config->unresolvedSymbols == UnresolvedPolicy::Warn) 1593 warn(Twine("symbol exported via --export not found: ") + name); 1594 } 1595 } 1596 1597 log("-- populateTargetFeatures"); 1598 populateTargetFeatures(); 1599 1600 // When outputting PIC code each segment lives at at fixes offset from the 1601 // `__memory_base` import. Unless we support the extended const expression we 1602 // can't do addition inside the constant expression, so we much combine the 1603 // segments into a single one that can live at `__memory_base`. 1604 if (config->isPic && !config->extendedConst && !config->sharedMemory) { 1605 // In shared memory mode all data segments are passive and initialized 1606 // via __wasm_init_memory. 1607 log("-- combineOutputSegments"); 1608 combineOutputSegments(); 1609 } 1610 1611 log("-- createSyntheticSectionsPostLayout"); 1612 createSyntheticSectionsPostLayout(); 1613 log("-- populateProducers"); 1614 populateProducers(); 1615 log("-- calculateImports"); 1616 calculateImports(); 1617 log("-- scanRelocations"); 1618 scanRelocations(); 1619 log("-- finalizeIndirectFunctionTable"); 1620 finalizeIndirectFunctionTable(); 1621 log("-- createSyntheticInitFunctions"); 1622 createSyntheticInitFunctions(); 1623 log("-- assignIndexes"); 1624 assignIndexes(); 1625 log("-- calculateInitFunctions"); 1626 calculateInitFunctions(); 1627 1628 if (!config->relocatable) { 1629 // Create linker synthesized functions 1630 if (WasmSym::applyDataRelocs) 1631 createApplyDataRelocationsFunction(); 1632 if (WasmSym::applyGlobalRelocs) 1633 createApplyGlobalRelocationsFunction(); 1634 if (WasmSym::applyGlobalTLSRelocs) 1635 createApplyGlobalTLSRelocationsFunction(); 1636 if (WasmSym::initMemory) 1637 createInitMemoryFunction(); 1638 createStartFunction(); 1639 1640 createCallCtorsFunction(); 1641 1642 // Create export wrappers for commands if needed. 1643 // 1644 // If the input contains a call to `__wasm_call_ctors`, either in one of 1645 // the input objects or an explicit export from the command-line, we 1646 // assume ctors and dtors are taken care of already. 1647 if (!config->relocatable && !config->isPic && 1648 !WasmSym::callCtors->isUsedInRegularObj && 1649 !WasmSym::callCtors->isExported()) { 1650 log("-- createCommandExportWrappers"); 1651 createCommandExportWrappers(); 1652 } 1653 } 1654 1655 if (WasmSym::initTLS && WasmSym::initTLS->isLive()) { 1656 log("-- createInitTLSFunction"); 1657 createInitTLSFunction(); 1658 } 1659 1660 if (errorCount()) 1661 return; 1662 1663 log("-- calculateTypes"); 1664 calculateTypes(); 1665 log("-- calculateExports"); 1666 calculateExports(); 1667 log("-- calculateCustomSections"); 1668 calculateCustomSections(); 1669 log("-- populateSymtab"); 1670 populateSymtab(); 1671 log("-- checkImportExportTargetFeatures"); 1672 checkImportExportTargetFeatures(); 1673 log("-- addSections"); 1674 addSections(); 1675 1676 if (errorHandler().verbose) { 1677 log("Defined Functions: " + Twine(out.functionSec->inputFunctions.size())); 1678 log("Defined Globals : " + Twine(out.globalSec->numGlobals())); 1679 log("Defined Tags : " + Twine(out.tagSec->inputTags.size())); 1680 log("Defined Tables : " + Twine(out.tableSec->inputTables.size())); 1681 log("Function Imports : " + 1682 Twine(out.importSec->getNumImportedFunctions())); 1683 log("Global Imports : " + Twine(out.importSec->getNumImportedGlobals())); 1684 log("Tag Imports : " + Twine(out.importSec->getNumImportedTags())); 1685 log("Table Imports : " + Twine(out.importSec->getNumImportedTables())); 1686 } 1687 1688 createHeader(); 1689 log("-- finalizeSections"); 1690 finalizeSections(); 1691 1692 log("-- writeMapFile"); 1693 writeMapFile(outputSections); 1694 1695 log("-- openFile"); 1696 openFile(); 1697 if (errorCount()) 1698 return; 1699 1700 writeHeader(); 1701 1702 log("-- writeSections"); 1703 writeSections(); 1704 if (errorCount()) 1705 return; 1706 1707 if (Error e = buffer->commit()) 1708 fatal("failed to write the output file: " + toString(std::move(e))); 1709 } 1710 1711 // Open a result file. 1712 void Writer::openFile() { 1713 log("writing: " + config->outputFile); 1714 1715 Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr = 1716 FileOutputBuffer::create(config->outputFile, fileSize, 1717 FileOutputBuffer::F_executable); 1718 1719 if (!bufferOrErr) 1720 error("failed to open " + config->outputFile + ": " + 1721 toString(bufferOrErr.takeError())); 1722 else 1723 buffer = std::move(*bufferOrErr); 1724 } 1725 1726 void Writer::createHeader() { 1727 raw_string_ostream os(header); 1728 writeBytes(os, WasmMagic, sizeof(WasmMagic), "wasm magic"); 1729 writeU32(os, WasmVersion, "wasm version"); 1730 os.flush(); 1731 fileSize += header.size(); 1732 } 1733 1734 void writeResult() { Writer().run(); } 1735 1736 } // namespace wasm 1737 } // namespace lld 1738